成员函数做友元
其实class A的作用不是告诉B有A类,而是告诉B有A这个数据类型,若是2中的情况,则需要在B前面整个定义完全的A类(个人理解)
#include<iostream>
using namespace std;
class test1;//声明标识符
class test2
{
public:
int c;
void fun(test1& t);//函数的声明
private:
int d;
};
/*void test2::fun(test1&t)//
{
cout << t.a << endl;//此处要知道test1类型的具体内容,
但是系统并不知道,虽然在上面声明的该类型,
但是我们不知道具体内容,具体内容在下面才给出,
所以会报错,提示未定义类型test1(我个人理解是这样的),
所以将该函数移动到test1类型后面就不报错了,
(个人理解,仅供参考,不一定正确)
cout << t.b << endl;
}*/
class test1
{
public:
int a;
friend void test2::fun(test1& t);//友元函数的声明
private:
int b;
};
void test2::fun(test1& t)//函数的定义(错误的根源)
{
cout << t.a << endl;
cout << t.b << endl;
}
int main()
{
test2 t2;
test1 t1;
t2.fun(t1);
}
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;
class Building;
class GoodGay
{
public:
GoodGay();
void visit();
void visit2();
private:
Building* building;//此处用到Building类,所以要在本类前声明有Building类
//c++中自动向上寻找
};
class Building
{
friend void GoodGay::visit();
public:
string sittingroom;
Building(); // 成员函数必须写在其所在类的后面,写在声明后也不行
private:
string bedroom;
};
GoodGay::GoodGay()
{
//因为此处用到Building,故虽然是GooGay类中的成员函数,也要放在Building类后面
building = new Building;
}
void GoodGay::visit()
{
cout << building->sittingroom << endl;
cout << building->bedroom << endl;
}
void GoodGay::visit2()
{
cout << building->sittingroom << endl;
}
Building::Building()
{
sittingroom = "keting";
bedroom = "woshi";
}
int main()
{
GoodGay gg;
gg.visit();
gg.visit2();
system("pause");
return 0;
}