The following codes try to show how to overload assignment operator:
#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;
}
However, when I compile it with VC10, I have found the following error:
error C2440: '==' : cannot convert from 'A<T> *' to 'A<T> *const '
If I change the overloading function in the following way:
template <typename E>
A<T>& operator = ( A<E> &obj)
{
// if(this == &obj)
// return *this;
value = obj.value;
return *this;
}
It will work. Why does this error occur in the commented-out code when called in this way?
You’re missing part of the error message. It should say:
You may have to look at nearby lines in the build log to see that extra information. And the compiler is doing no favors by using
Ttwice but representing two different types.