1.先看代码
#include<bits/stdc++.h> using namespace std; class GoodGay; //类声明 class Building;//类声明 class GoodGay{
public: GoodGay();//构造函数声明后类外实现 ~GoodGay();//析构函数声明后类外实现 void visit(); /* visit()函数声明后要类外实现, 因为visit里面访问了Building类的成员变量 所以visit()函数的实现要写在Buliding类定义的后面 但是Building类里面又要求GoodGay的定义在Building类前面 因为这样Building类里的友元声明才能知道GoodGay类里面是不是 真的有visit()这个成员函数 所以类内定义类外实现的作用就体现在这里了 */ private: Building * building; }; class Building{
friend void GoodGay::visit(); /* 虽然GoodGay类已经声明了 但是Building类还不知道GoodGay类具体有哪个函数, 所以要把Building类的定义放在GoodGay类的定义下面 */ public: Building(){
m_SittingRoom = "客厅"; m_BedRoom = "卧室"; } public: string m_SittingRoom; private: string m_BedRoom; }; void GoodGay::visit(){
//函数类型要写在前面 cout << "好友真正访问你家的: " << building->m_SittingRoom << '\n'; cout << "好友真正访问你家的: " << building->m_BedRoom << '\n'; } GoodGay::GoodGay(){
//GoodGay构造函数类外实现 //创建建筑物对象 building = new Building; } GoodGay::~GoodGay(){
delete building; } void test1(){
GoodGay gg; gg.visit(); } int main(){
test1(); return 0; }
讯享网
2.代码说明
1.GoodGay类定义要在Building类定义前面
虽然GoodGay类已经声明了,
但是Building类还不知道GoodGay类具体有哪个函数可以设置成友元,
所以要把GoodGay类定义在Building类的前面.
2.visit()函数声明后要类外实现
因为GoodGay里的visit()函数里面访问了Building类的成员变量,
所以visit()函数的实现要写在Buliding类定义的后面,
但是Building类里面又要求GoodGay类的定义在Building类前面.
这就矛盾了
所以只能把visit()函数的实现从类中拿出来,类外实现在Building类定义后面,所以类内声明类外实现的作用就体现在这里了.

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/63840.html