【发布时间】:2016-10-29 14:57:18
【问题描述】:
我试图重载赋值运算符,但它似乎不起作用。 The code is based on this answer。我搜索了其他重载赋值运算符的示例,但我的代码似乎不应该运行。
这是我的代码:
#pragma once
#include <assert.h>
class ReadOnlyInt
{
public:
ReadOnlyInt(): assigned(false) {}
ReadOnlyInt& operator=(int v);
operator int() const ;
private:
int value;
bool assigned;
};
ReadOnlyInt& ReadOnlyInt::operator=(int v)
{
assert(!assigned);
value = v;
assigned = true;
return *this;
}
ReadOnlyInt::operator int() const
{
assert(assigned);
return value;
}
Intellisense 不发出任何警告,但 operator= 未突出显示为关键字。
现在,如果我进行分配,Intellisense 确实认识到这是不可能的:
ReadOnlyInt bar = 12;
没有合适的构造函数将“int”转换为“ReadOnlyInt”
但是这可行:
int foo = bar;
解决方案
这个问题被标记为重复,所以我无法回答。这是我根据 cmets 提出的解决方案并回答了这个问题:
ReadOnlyInt::ReadOnlyInt()
: assigned(false)
{}
ReadOnlyInt::ReadOnlyInt(int v)
: value(v), assigned(true)
{}
【问题讨论】:
-
如果你做
ReadOnlyInt bar然后分配bar = 12;是否有效 -
ReadOnlyInt bar = 12;不做作业;这是复制初始化。要使用分配,请创建对象并单独分配给它:ReadOnlyInt bar; bar = 12;.
标签: c++ visual-c++ operator-overloading overloading