【发布时间】:2017-11-20 21:32:14
【问题描述】:
我想知道在初始化/比较对象与特定类型的变量时是否有禁用 (?) 类型转换的选项:
class X {
//...
const bool operator<=(const long long val) const;
const bool operator<=(const char* val) const;
const X& operator=(const long long val);
const X& operator=(const char* val);
}
int main() {
X x1 = 10; //thats ok
X x2 = "123"; //ok again
X x3 = 0; //error, 0 is 'valid' char*
x1 <= 0 ? true : false; //error, same reason
}
这是错误:more than one operator "<=" matches these operands
有没有办法摆脱这些错误?
我知道我可以输入main,但不幸的是这不是我想要的,或者实际上什至不允许这样做:
X x3 = (long long)0; //no no no...
另外 - 没有std::string。
回答(部分)
所以赋值部分可以通过改变类声明来解决 - 摆脱long long赋值并使适当的构造函数显式/隐式
// allow implicit conversion from long long, ex. X x = 13;
X(long long val)
// disable implicit conversion from const char*, now X x = 0 is ok - calls the above
explicit X(const char* val);
// allow assignment from const char as well, no confusion with 0 now
const X& operator=(const char*);
【问题讨论】:
-
如果您可以摆脱赋值运算符并用explicit constructors 替换它们,您将摆脱错误。但是,不可能有明确的分配。
-
谢谢@RainingChain ,@a-a 我按照您的建议运行了作业,但仍然没有正确设置
<=运算符,您还有其他建议吗?还是我还缺少什么? -
添加一个采用
int的重载。0更喜欢char*。 -
后缀是一个选项吗?例如。
X x3 = 0ll;
标签: c++11 casting operator-overloading c-strings