看到C++书上说友元函数就是为了别人能访问类中的私有成员设计,感觉挺好就给记下了。 看下面的例子: #include <cstdlib> #include <iostream> using namespace std; class C2; class C1{ private: int a; int b; public: C1(int temp){a=temp;b=temp;} void show(){cout << a << "-" << b << endl;} ~C1(){} friend int Myfriend(C1 &ob1,C2 &ob2); }; class C2{ private: int c; int d; public: C2(int temp){c=temp;d=temp;} void show(){cout << c << "-" << d << endl;} ~C2(){} friend int Myfriend(C1 &ob1,C2 &ob2); }; int Myfriend(C1 &ob1,C2 &ob2) { ob2.c=ob1.a;//这里把类C1中的私有成员值赋给C2中的私有成员 ob2.d=ob1.b; return 0; } int main(int argc, char *argv[]) { C1 o1(10); C2 o2(20); o1.show(); o2.show(); Myfriend(o1,o2); o1.show(); o2.show(); return 0; } //以上代码中DEV-C++ 4.9.9.2编译通过 //输出结果: //10-10 //20-20 //10-10 //10-10 如上就实现了两个不同的类私有成员的数据访问。