友员函数和友员类

#include<iostream>

using namespace std;

class Test2//注意友员类的定义放在Test1的之上!!

{

friend class Test1;//Test1想直接访问Test2的private参数,所以声明为我是你的朋友!

public:

Test2(int a, int b){ x = a; y = b; }

int getx(){

return x;

}

int gety(){

return y;

}

private:

int x, y;

};

class Test1{

public:

Test1(int a, int b) :t(a, b){}

void print(){ cout << "Test2 的对象t的x:" << t.x << endl; }

private:

Test2 t;//因为Test2是Test1的友员


};

class Test3{

public:

friend int getTx(Test3 & t3);//友员函数通过类的指针或引用访问这个类对象的私有成员

private:

//friend int getTx(Test3 & t3);//放在这里完全一样,访问限制符对友员函数不管用

int x;

};

int getTx(Test3 & t3){//友员函数在类外定义!不加static防止给别的混淆

return t3.x;//友员函数可以使用类的所有函数

}

int main(){

Test1 t1(2,5);

t1.print();

system("pause");

return 0;


}