1.友元函数
1.class
class MM { public:MM(int age,string name):age(age),name(name){}friend void print(MM mm); private:int age;string name;void print() {cout << age << "岁的" << name << "喜欢你" << endl;} };
friend 函数的编写
void print(MM mm) {mm.print();//print为私有函数,函数设为友元函数时可以使用 }
2.main
int main() {MM mm(18, "女神");print(mm);return 0; }
3.结果:
2.友元函数(这个函数是另一个类函数)
1.class
class boy { public:static void boyLove(); }; class MM { public:MM(int age,string name):age(age),name(name){}friend void boy::boyLove(); private:int age;string name;void print() {cout << age << "岁的" << name << "喜欢你" << endl;} };
2.实现friend函数
void boy::boyLove() {MM mm(10, "女生");mm.print(); }
3.main
int main() {MM mm(18, "女神");boy::boyLove();return 0; }
4.结果: