为了更好地理解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;
}
然后这行主要功能给出了错误:
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
最佳答案
该功能
T PlusTen (T obj)
{
T newObj(5);
newObj.set( obj.get() +10 );
return newObj;
}
返回类型为
T
的临时对象。这个临时对象可以绑定(bind)一个常量引用。因此,编译器会发出错误,因为赋值运算符的参数
T& operator= (T& obj)
^^^^^^
不是恒定引用。
无论上下文如何,返回类型中的限定符
const
都无关紧要。关于c++ - 无法理解赋值运算符的重载,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36159099/