友元函数是一个全局函数,和我们写的全局函数类似,只是友元函数可以访问某个类私有数据。
案例: 重载左移操作符(<<),使得cout可以输出对象。
class Person{ friend ostream& operator<<(ostream& os, Person& person); public: Person(int id,int age){ mID = id; mAge = age; } private: int mID; int mAge; }; ostream& operator<<(ostream& os, Person& person){ os << "ID:" << person.mID << " Age:" << person.mAge; return os; } int main(){ Person person(1001, 30); //cout << person; //cout.operator+(person) cout << person << " | " << endl; return EXIT_SUCCESS; }