eth*_*han 3 c++ casting conditional-operator implicit-conversion
在C++中,我试图使用条件运算符进行隐式转换.考虑这个例子:
class MyFloat
{
public:
MyFloat(float val){m_val = val;}
operator float(){return m_val;}
protected:
float m_val;
};
int main(int argc, char **argv)
{
MyFloat a = 0.5f;
MyFloat b = 1.0f;
float x = true ? a-0.5f : b;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它会导致编译器错误:
error: operands to ?: have different types ‘MyFloat’ and ‘float’
Run Code Online (Sandbox Code Playgroud)
我希望条件运算符隐式转换b为a-0.5float 类型.但这不会发生.我如何实现这种隐式演员?
理想情况下,我想避免静态强制转换或访问方法float MyFloat::getValue().