[英]Implicit conversion in C++
In C++, I'm trying to use implicit conversion with a conditional operator. 在C ++中,我试图使用条件运算符进行隐式转换。 Consider this example:
考虑这个例子:
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;
}
It causes a compiler error: 它会导致编译器错误:
error: operands to ?: have different types ‘MyFloat’ and ‘float’
I expect the conditional operator to implicitly convert b
to the type of a-0.5
, float. 我希望条件运算符隐式地将
b
转换为a-0.5
,float的类型。 But this does not happen. 但这不会发生。 How do I achieve this implicit cast?
我如何实现这种隐式演员?
Ideally, I want to avoid a static cast or an accessor method like float MyFloat::getValue()
. 理想情况下,我想避免静态
float MyFloat::getValue()
或访问器方法,如float MyFloat::getValue()
。
The problem is that there are two conversions. 问题是有两次转换。 The compiler can convert
a-0.5
to MyFloat
or it can convert b
to float
. 编译器可以将
a-0.5
转换为MyFloat
,也可以将b
转换为float
。 As long as you have both conversions and neither is marked explicit
you'll get this kind of ambiguity all the time. 只要您同时进行了两次转换,并且两者都没有
explicit
标记,您就会始终获得这种模糊性。
Only some conversions are done for you. 只为您完成了一些转换。 From http://msdn.microsoft.com/en-us/library/e4213hs1(v=vs.71).aspx
来自http://msdn.microsoft.com/en-us/library/e4213hs1(v=vs.71).aspx
The first operand must be of integral or pointer type. 第一个操作数必须是整数或指针类型。 The following rules apply to the second and third expressions:
以下规则适用于第二个和第三个表达式:
The ternary operator doesn't do any implicit casting if I remember correctly. 如果我没记错的话,三元运算符不会进行任何隐式转换。 You will need to either write
你需要写
static_cast<MyFloat>(a-0.5)
or 要么
static_cast<float>(b).
I'll dig through the C++ standards doc when I get home for more details. 当我回到家中获取更多细节时,我将深入研究C ++标准文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.