一些C++错误及解决方法

成员函数做友元

 其实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;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值