> 文章列表 > operator<< 重载为什么需要是类的friend函数

operator<< 重载为什么需要是类的friend函数

operator<< 重载为什么需要是类的friend函数

当一个类中定义某个类外的函数为friend(友元)函数时,这个friend函数可以访问该类的private成员变量。
那么当重载operator<<时,为什么需要是类的友元函数?
具体例子如下,print函数的实现,是希望通过operator<<重载来输出Test类的具体信息,这个时候print里的这句话“cout<<*this”,相当于调用函数operator<<(cout, this);如果不是友元函数,那么operator<<是无法访问this的。

操作符的重载具体可以参考这个文章,写的很好:https://condor.depaul.edu/ntomuro/courses/262/notes/lecture3.html

#include
using namespace std;

class Test {
public:
Test(int i) {
m_data = i;
}
int getData() {
return m_data;
}
void print()
{
cout<<*this<<endl;
}
friend ostream& operator<<(ostream& os, Test& t);

private:
int m_data;

};

ostream& operator<<(ostream& os, Test& t) {
os << “data:” << t.getData() << endl;
return os;
}

int main() {
// Write C++ code here
std::cout << “Hello world!”;
Test t(10);
t.print();
return 0;
}