【发布时间】:2010-11-29 12:55:05
【问题描述】:
class Foo {
public:
explicit Foo(double item) : x(item) {}
operator double() {return x*2.0;}
private:
double x;
}
double TernaryTest(Foo& item) {
return some_condition ? item : 0;
}
Foo abc(3.05);
double test = TernaryTest(abc);
在上面的例子中,如果 some_condition 为真,为什么 test 等于 6(而不是 6.1)?
如下更改代码返回值 6.1
double TernaryTest(Foo& item) {
return some_condition ? item : 0.0; // note the change from 0 to 0.0
}
似乎(在原始示例中)来自 Foo::operator double 的返回值被强制转换为 int,然后返回为 double。为什么?
【问题讨论】:
-
它与条件运算符无关。这也打印 6。不过,我不知道为什么。 #include
class Foo { public: explicit Foo(double item) : x(item) {} operator double() {return x * 2;} private: double x; }; int main(){ Foo abc(3.05);双重测试= abc; printf("%.f\n", 测试);返回0; } -
@cube: 因为
%.f打印 0 个小数位。 -
看起来反转条件也解决了问题 - 返回 some_condition ? 0:项目;
标签: c++ ternary-operator ternary