【发布时间】:2016-03-22 15:50:29
【问题描述】:
为了更好地理解 c++ 中对象的工作原理,我编写了这段代码:
using namespace std;
char n[] = "\n";
class T
{
private:
int num;
public:
T ()
{
num = 0;
cout << n << (long)this % 0xFF << " created without param";
}
T (const int param)
{
num = param;
cout << n << (long)this % 0xFF << " created with param = " << param;
}
T (const T& obj)
{
num = obj.num;
cout << n << (long)this % 0xFF << " created as copy of " << (long)&obj % 0xFF;
}
const T& operator= (const T& obj)
{
if (this == &obj)
return *this;
num = obj.num;
cout << n << (long)this % 0xFF << " got assigned the data of " << (long)&obj % 0xFF;
return *this;
}
~T ()
{
cout << n << (long)this % 0xFF << " destroyed";
}
int get () const {return num;}
void set (const int param) {num = param;}
};
T PlusTen (T obj)
{
T newObj(5);
newObj.set( obj.get() +10 );
return newObj;
}
int main ()
{
T a, b(4);
a = b;
a = PlusTen(b);
cout << n;
return 0;
}
它工作正常,但是当我删除重载赋值运算符的“返回类型”和“参数”中的const 限定符时,如下所示:
T& operator= (T& obj) // const removed
{
if (this == &obj)
return *this;
num = obj.num;
cout << n << (long)this % 0xFF << " got assigned the data of " << (long)&obj % 0xFF;
return *this;
}
那么这行main函数报错:
a = PlusTen(b);
错误信息是:
no match for 'operator=' (operand types are 'T' and 'T')
note:
candidate is: T& T::operator=(T&)
no known conversion for argument 1 from 'T' to 'T&'
如果 'T' 和 'T' 的操作数类型有问题,为什么它上面的行 (a = b;) 完全没问题?它们也是操作数类型 'T' 和 'T' !!
我在这里找到了一个相关的问题,但那里没有有用的细节:
why must you provide the keyword const in operator overloads
那里的一个人说,如果我们在 operator= 中不使用const,我们只能将它用于non-const 对象。但就我而言,双方也是非常量的。那为什么会出错呢?尤其是当它上面的行,它的操作数类型相同时,编译得很好?
使用的编译器:MinGW
【问题讨论】:
标签: c++ class operator-overloading constants