错误例程:
#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;
}