在下面的代码,我说明运算符重载的例子:为什么运算符重载失败?
#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 = (const A<E> &obj)
{
cout<<"equal operator"<<endl;
if(this == &obj)
return *this;
value = obj.value;
return *this;
}
};
int main()
{
int temp;
temp = 3;
A<int> myobjects(temp);
cout<<myobjects.value<<endl;
temp = 7;
A<int> yourobjects(temp);
yourobjects = myobjects;
cout<<yourobjects.value<<endl;
return 0;
}
然而,当我调试这个程序,我发现主程序不会调用等于运算符重载功能。但是,如果我通过以下方式更改相同的运营商:
A<T>& operator = (const A<T> &obj)
{
cout<<"equal operator"<<endl;
if(this == &obj)
return *this;
value = obj.value;
return *this;
}
它会工作。你有什么想法,为什么最初的功能不起作用?
需要注意的是,最好把这种现象称为了_assignment_操作。 _equal_运算符是'=='。 – 2012-07-09 17:21:42