类模板友元函数坑死人不偿命的错误

错误例程:

#include<iostream>

using namespace std;

template<class T>
class Student
{
private:
	T age;
public:
	Student(T age_) :age(age_){}
	friend bool operator==(const Student<T>& s1, const Student<T>& s2);
};

int main()
{
	Student<int> s1(1);
	Student<int> s2(2);
	if (s1 == s2)
		cout << "相等" << endl;
	else
		cout << "不相等" << endl;

	cin.get();
	return 0;
}

template<class T>
bool operator==(const Student<T>& s1, const Student<T>& s2)
{
	if (s2.age == s1.age)
	{
		return true;
	}
	return false;
}

今天敲代码时一个类似于上面的程序报错了,报错原因是比较s1和s2的==运算符没有定义。我勒个擦,看了N长时间,愣是没有看出哪里错来,然后就放了放,晚上的时候又问了一个大神,结果大神也没看出来/(ㄒoㄒ)/~~。最后终于发现了,原来是类中的友元函数的声明的参数中的类模板类型直接用的类的模板类型了,没有自己template,编译器检查不出来,导致了类中的友元函数的声明与类外友元函数的实现对接不上,导致了==运算符没有定义的错误。


正确例程:

#include<iostream>

using namespace std;

template<class T>
class Student
{
private:
	T age;
public:
	Student(T age_) :age(age_){}

	template<class T>
	friend bool operator==(const Student<T>& s1, const Student<T>& s2);
};

int main()
{
	Student<int> s1(1);
	Student<int> s2(2);
	if (s1 == s2)
		cout << "相等" << endl;
	else
		cout << "不相等" << endl;

	cin.get();
	return 0;
}

template<class T>
bool operator==(const Student<T>& s1, const Student<T>& s2)
{
	if (s2.age == s1.age)
	{
		return true;
	}
	return false;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值