深海潜水员 发表于 2020-5-26 11:04:53

左移右移运算符重载,必须加友元吗?

本帖最后由 深海潜水员 于 2020-5-26 11:04 编辑

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;

class Person
{
public:
        Person(const string name, const int age);

public:
        string m_Name;
        int m_Age;
};

Person::Person(const string name, const int age)
{
        this->m_Age = age;
        this->m_Name = name;
}

ostream & operator<<(ostream & out, const Person & p)
{
        out << "Name = " << p.m_Name << '\t' << "Age = " << p.m_Age;
        return out;
}

int main()
{
        Person p1("Tom", 100);
        cout << p1 << endl;

        system("pause");
        return 0;
}

永恒的蓝色梦想 发表于 2020-5-26 11:07:52

是的,因为这是给 ostream 对象的左移重载,不是给 Person 对象的左移重载。

sunrise085 发表于 2020-5-26 11:57:49

不是的。你的这个程序不就没有加友元么?
之所以加友元是因为很多时候类的成员变量属性都是private,不加友元无法直接访问类成员变量。
但若重载运算符时,用到的都是公有成员,那就可以不加友元。

深海潜水员 发表于 2020-5-26 12:41:41

sunrise085 发表于 2020-5-26 11:57
不是的。你的这个程序不就没有加友元么?
之所以加友元是因为很多时候类的成员变量属性都是private,不加 ...

谢谢,听君一席话胜读十年书!{:10_257:}
页: [1]
查看完整版本: 左移右移运算符重载,必须加友元吗?