好的,所以我有一个具有“弱类型”IE 的类,它可以存储许多不同的类型,定义为:
#include <string>
class myObject{
public:
bool isString;
std::string strVal;
bool isNumber;
double numVal;
bool isBoolean;
bool boolVal;
double operator= (const myObject &);
};
我想像这样重载赋值运算符:
double myObject::operator= (const myObject &right){
if(right.isNumber){
return right.numVal;
}else{
// Arbitrary Throw.
throw 5;
}
}
这样我就可以做到这一点:
int main(){
myObject obj;
obj.isNumber = true;
obj.numVal = 17.5;
//This is what I would like to do
double number = obj;
}
但是当我这样做时,我得到:
error: cannot convert ‘myObject’ to ‘double’ in initialization
在任务中。
我也试过:
int main(){
myObject obj;
obj.isNumber = true;
obj.numVal = 17.5;
//This is what I would like to do
double number;
number = obj;
}
我得到:
error: cannot convert ‘myObject’ to ‘double’ in assignment
有什么我想念的吗?还是根本不可能通过重载来进行这样的转换operator=
。