C++学习一错误解决_类型未定义

在C++学习中,使用友元函数时,大多会遇到这样的问题。比如下面的友元全局函数的使用,就存在问题

//友元全局函数
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
class Test;
void fun(Test & test) {
	cout << test.m_strName << endl;
}
class Test {
	friend void fun(Test & test);
public:
	Test(string name):m_strName(name){}
private:
	string m_strName;
};
int main(void) {
	Test a("name");
	fun(a);
	system("pause");
	return 0;
}
这里编译时就会报错:Line 8:Test类型未定义。

但是,这就纳闷了。我不是在之前写了class Test;声明了吗?

有这样的感觉是正常的,因为你没理解一个注意。使用类的声明,系统只知道有这样一个声明,并不知道有什么成员。这样在定义和声明之间就只能使用这个类型的引用或者指针

但是在这里的代码中第八行却使用了他的成员。如果把cout << test.m_strName << endl;注释掉,可以正常编译.这就能证明这点。

解决方法有两种:

第一种,把fun全局函数放到后面来。(这种方法适用于友元全局函数)

第二种,是函数的声明写在这里,定义写在需要使用的类的后面。(这种方法,在友元成员函数的定义时是非常有效的,而且某些情况只能使用这种方法,例如下面的代码)

#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
class Test2;

class Test1 {
public:
	void fun(Test2 & t) {
		cout << t.m_strName << endl;
	}
};

class Test2 {
	friend void Test1::fun(Test2 & t);
public:
	Test2(string name): m_strName(name){}
private:
	string m_strName;
};

int main() {
	Test2 t2("name");
	Test1 t1;
	t1.fun(t2);
	system("pause");
	return 0;
}
你两个类怎么换都会出错。所以只能使用第二种方法。定义和声明分开。下面就是这样。
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
class Test2;

class Test1 {
public:
	void fun(Test2 & t);
};

class Test2 {
	friend void Test1::fun(Test2 & t);
public:
	Test2(string name): m_strName(name){}
private:
	string m_strName;
};

void Test1::fun(Test2 & t) {
	cout << t.m_strName << endl;
}

int main() {
	Test2 t2("name");
	Test1 t1;
	t1.fun(t2);
	system("pause");
	return 0;
}





评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值