zmb*_*ush 5 c++ operator-overloading operators type-conversion conversion-operator
好的,所以我有一个类'弱键入'IE它可以存储许多不同的类型定义为:
#include <string>
class myObject{
public:
bool isString;
std::string strVal;
bool isNumber;
double numVal;
bool isBoolean;
bool boolVal;
double operator= (const myObject &);
};
Run Code Online (Sandbox Code Playgroud)
我想像这样重载赋值运算符:
double myObject::operator= (const myObject &right){
if(right.isNumber){
return right.numVal;
}else{
// Arbitrary Throw.
throw 5;
}
}
Run Code Online (Sandbox Code Playgroud)
所以我可以这样做:
int main(){
myObject obj;
obj.isNumber = true;
obj.numVal = 17.5;
//This is what I would like to do
double number = obj;
}
Run Code Online (Sandbox Code Playgroud)
但当我这样做时,我得到:
error: cannot convert ‘myObject’ to ‘double’ in initialization
Run Code Online (Sandbox Code Playgroud)
在任务.
我也尝试过:
int main(){
myObject obj;
obj.isNumber = true;
obj.numVal = 17.5;
//This is what I would like to do
double number;
number = obj;
}
Run Code Online (Sandbox Code Playgroud)
我得到了:
error: cannot convert ‘myObject’ to ‘double’ in assignment
Run Code Online (Sandbox Code Playgroud)
有什么我想念的吗?或者根本不可能通过重载进行转换operator=.
CB *_*ley 12
重载operator=分配时,改变行为,以你的类的对象.
如果要为其他类型提供隐式转换,则需要提供转换运算符,例如
operator double() const
{
if (!isNumber)
throw something();
return numVal;
}
Run Code Online (Sandbox Code Playgroud)
您真正想要的是转换运算符.
operator double() const { return numVal; }
operator int() const { ...
Run Code Online (Sandbox Code Playgroud)
那就是说,你可能会喜欢boost :: variant.