【发布时间】:2021-12-04 19:38:15
【问题描述】:
我有这个类SmallInt,它应该表示0-255-inclusive 范围内的正整数值:
struct SmallInt{
explicit SmallInt(int x = 0) : iVal_( !(x < 0 || x > 255) ? x :
throw std::runtime_error(std::to_string(x) + ": value outbounds!")){}
operator int&() { return iVal_; }
int iVal_;
};
int main(){
try{
SmallInt smi(7);
cout << smi << '\n';
cout << smi + 5 << '\n'; // 7 + 5 = 12
cout << smi + 5.88 << '\n'; // 7.0 + 5.88 = 12.88
smi = 33; // error: constructor is explicit
smi.operator int&() = 33;
cout << smi << '\n';
}
catch(std::runtime_error const& re){
std::cout << re.what() << '\n';
}
}
-
我重要的是:为什么我可以分配给
smi,显式调用operator int&:smi.operator int&() = 33,但不能隐式调用:smi = 33;? -
第一个表达式(
smi = 33;)抱怨构造函数SmallInt(int)beginexplicit;我知道,但我有返回可修改的普通左值的转换运算符。那么换句话说,为什么在这样的隐式赋值中,构造函数优于转换运算符?
【问题讨论】:
-
这个问题应该有
language-lawyer标签。 -
疯狂猜测:
33的类型是int&&,而不是int& -
@Raildex 这是
int类型的prvalue。表达式不能有引用类型。 -
我想
smi = 33;被解释为smi.operator=(33);,它必须将33转换为SmallInt才能传递参数,从而寻找合适的构造函数。 -
如果你添加一个显式类型转换它可以工作:
(int&) smi = 33;所以我猜它只会尝试转换 operator= 的右侧,因为你不想转换你的值想分配给
标签: c++ implicit-conversion conversion-operator explicit-constructor