对于一个类的私有成员,只有类的成员函数才能直接访问。外部的类或者函数想要访问就必须给予它权利,也就是设置成该类的友元(friend)。
#include#include using namespace std; class currency { //建立友元 friend ostream& operator<<(ostream& out, const currency& x); public: currency(int init = 0) { amount = init; } currency &increase(const currency& x) { amount += x.amount; return *this; } /*void output(ostream& out) const { int theAmount = amount; int dollars = theAmount / 100; out << '$' << dollars << "."; int cents = theAmount - dollars * 100; if (cents < 10) out << '0'; out << cents; }*/ currency operator+(const currency &x) const { currency d; d.amount = amount + x.amount; return d; } currency& operator+=(const currency &x) { amount += x.amount; return *this; } private: int amount; }; //友元函数 ostream& operator<<(ostream& out, const currency& x) { /*x.output(out);*/ int theAmount = x.amount; //因为是友元,所以才能访问x的私有数据成员amount int dollars = theAmount / 100; out << '$' << dollars << "."; int cents = theAmount - dollars * 100; if (cents < 10) out << '0'; out << cents; return out; } int main() { currency a; currency b(100); currency c; c = a+b; cout << c << endl; c += c; cout << c<