在以下代码中,我举例说明了运算符重载的示例:
#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;
}
它会起作用的。你有什么想法为什么初始功能不起作用?