c++之友元

c++之友元,第1张

概述客厅:客人可以随意走动;卧室:只有自己能进去; 现在想要自己的好朋友可以进去,就需要用到友元技术。即友元的目的就是让一个函数或者类访问另一个类中私有成员。 关键字:friend 三种实现方法: 全局函

客厅:客人可以随意走动;卧室:只有自己能进去;

现在想要自己的好朋友可以进去,就需要用到友元技术。即友元的目的就是让一个函数或者类访问另一个类中私有成员。

关键字:frIEnd

三种实现方法:

全局函数做友元类做友元成员函数做友元

全局函数做友元:

#include<iostream>using namespace std;class Building{    frIEnd voID goodGay(Building* building);public:    Building() {        room = "客厅";        myRoom = 卧室;    }:    string room;private myRoom;};//全局函数voID goodGay(Building *building) {    cout << 好朋友正在访问" <<building->room<< endl;    如果不将dooGay变成Building的友元函数,这里就会报错    cout << "好朋友正在访问" << building->myRoom << endl;}voID test() {    Building building;    goodGay(&building);}int main() {    test();    system(pause);    return 0;}

类做友元:

说明:在类外定义成员函数时,需要先在类中声明函数。利用类名::函数名(),可以定义类的成员函数。

#include<iostream> std; Building{    frIEnd class GoodGay; room;    Building();类外写成员函数Building::Building() {    room = ;    myRoom = ;} GoodGay {:    Building* building;    GoodGay();     visit();};GoodGay::GoodGay() {    building = new Building();} GoodGay::visit() {    cout << 好基友类正在访问:" << building->room << endl;    cout << "好基友类正在访问:" << building->myRoom << test() {    GoodGay gg;    gg.visit();}成员函数做友元:

#include<iostream> Building; GoodGay;要先定义GoodGay类。。。我尝试在Building之后定义,就不行,之前也先声明了这两个类:    GoodGay();    voID visit();让该函数可以访问Building的私有成员     visit2(); building;};voID GoodGay::visit();;}GoodGay::GoodGay() {    building =  endl;    cout  GoodGay::visit2() {    cout << cout << "好基友类正在访问:" << building->myRoom << endl;} test2() {    GoodGay gg;    gg.visit2();};}
总结

以上是内存溢出为你收集整理的c++之友元全部内容,希望文章能够帮你解决c++之友元所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1159072.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-01
下一篇 2022-06-01

发表评论

登录后才能评论

评论列表(0条)

保存