该friend关键字是用来给其他类和函数访问类的private和protected成员,甚至通过他们的class`s范围之外定义。
class Animal{ private: double weight; double height; public: friend void printWeight(Animal animal); friend class AnimalPrinter; // A common use for a friend function is to overload the operator<< for streaming. friend std::ostream& operator<<(std::ostream& os, Animal animal); }; void printWeight(Animal animal) { std::cout <<animal.weight<< "\n"; } class AnimalPrinter { public: void print(const Animal& animal) { // Because of the `friend class AnimalPrinter;" declaration, we are // 允许在这里访问私有成员。 std::cout <<animal.weight<< ", " <<animal.height<< std::endl; } } std::ostream& operator<<(std::ostream& os, Animal animal) { os << "动物身高: " <<animal.height<< "\n"; return os; } int main() { Animal animal = {10, 5}; printWeight(animal); AnimalPrinter aPrinter; aPrinter.print(animal); std::cout << animal; }
10 10, 5 动物身高: 5