本文主要是介绍C++学习练习 之友元,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
C++学习练习
之友元
#include<iostream>
using namespace std;
class Building{//good全局函数是Building的好朋友,可以访问Building的私有成员friend void good(Building &building);public:Building(){m_SittingRoom = "客厅";m_BedRoom = "卧室";}public:string m_SittingRoom; //客厅private:string m_BedRoom; //卧室
};//全局函数
void good(Building &building){cout << "好朋友的全局函数正在访问:" << building.m_SittingRoom << endl;cout << "好朋友的全局函数正在访问:" << building.m_BedRoom << endl;
}void test01(){Building building;good(building);
}int main(){test01();system("pause");return 0;
}
成员函数做友元
#include<iostream>
using namespace std;
class Building;
class Good{public:Good();void visit(); // 让visit()函数可以访问Building中私有成员void visit02(); //让visit()函数不可以访问Building中私有成员Building * building;
};class Building{//告诉编译器 Good类下的 visit()成员函数作为本类的好朋友,可以访问私有成员friend void Good:: visit();public:Building();public:string m_SittingRoom; //客厅private:string m_BedRoom; //卧室
};//类外实现成员函数
Building:: Building(){m_SittingRoom = "客厅";m_BedRoom = "卧室";
}Good:: Good(){building = new Building;
}void Good:: visit(){cout << "visit() 函数正在访问: " << building->m_SittingRoom << endl;cout << "visit() 函数正在访问: " << building->m_BedRoom << endl;
}
void Good:: visit02(){cout << "visit2() 函数正在访问: " << building->m_SittingRoom << endl;// cout << "visit2() 函数正在访问: " << building->m_BedRoom << endl;
}void test01(){Good gg;gg.visit();gg.visit02();
}
int main(){test01();system("pause");return 0;
}
学习资源:https://www.bilibili.com/video/BV1et411b73Z?p=118
https://www.bilibili.com/video/BV1et411b73Z?p=120
这篇关于C++学习练习 之友元的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!