以下代码尝试显示如何重载赋值运算符:
#include <iostream>
using namespace std;
template <typename T>
class A
{
public:
A() {};
A( T &obj) {value = obj;};
~A() {};
T value;
template <typename E>
A<T>& operator = ( A<E> &obj)
{
if(this == &obj)
return *this;
value = obj.value;
return *this;
}
};
int main()
{
int temp;
temp = 3;
A<int> myobjects(temp);
cout<<myobjects.value<<endl;
float f_value;
f_value = 10.7;
A<float> fobjects(f_value);
myobjects = fobjects;
cout<<myobjects.value<<endl;
return 0;
}
但是,当我用VC10编译它时,我发现了以下错误:
error C2440: '==' : cannot convert from 'A<T> *' to 'A<T> *const '
如果我通过以下方式更改重载函数:
template <typename E>
A<T>& operator = ( A<E> &obj)
{
// if(this == &obj)
// return *this;
value = obj.value;
return *this;
}
它会起作用的。为什么这样调用时注释掉的代码会出现这个错误?