温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

友员函数和友员类

发布时间:2020-08-05 08:38:25 来源:网络 阅读:371 作者:神迹难觅 栏目:编程语言

#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;


}


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI