友元函数也是通过对象来访问类中的成员:
#include<iostream> using namespace std; class Love { public: // void show2() //--------------------------------通过调用show2可以输出 // { // int b=10; // a=b; // cout<<a<<endl;} friend void show(); private: int a; }; void show() //------------------------------通过友元函数也可以。 { Love A; int c=10; A.a=c; cout<<A.a<<endl;} int main() { // Love a; // a.show2(); show(); } ~
当然也可以通过这样的形式来访问,只不过这样相当于是把类的成员定义在了外面而已:
#include<iostream> using namespace std; class Love { public: void show(); private: int a; }; void Love::show() { int c=10; a=c; cout<<a<<endl;} int main() { Love b; b.show(); }