2012-09-14 22 views
4

为什么如果(var)...使用数字转换而不是布尔值? 我有一个同时实现了一类:“if(var)”使用数字转换而不是布尔值

operator int() { ....} 
operator bool() { ....} 

,但如果我使用:

if (my_class_var) ....; 

那么int转换是用来代替boolean!?!编辑: 由于versedmarald说这是正确的。我发现有什么不同..我实际上用的是:

operator int() { ....} 
operator bool() const { ... } 

还是着迷了,为什么不同? gcc版本4.6.2

+0

不知道答案,但只是我的好奇心:它如果通过强制转换使用bool(例如'if((bool)my_var)')? – nico

+0

你确定吗?如果你说的是真的,那听起来像是一个编译器错误。 Visual C++使用'运算符bool()'转换。 –

+5

Atleast [gcc-4.3.4使用bool运算符重载](http://ideone.com/Ko3Vn)。你使用什么编译器? –

回答

1

它没有(至少使用g++)。我的猜测是你的转换运算符有错误。

#include <iostream> 
class A { 
public: 
    operator int() { return 1; } 
}; 

class B { 
public: 
    operator int() { return 1; } 
    operator bool() { return false; } 
}; 

int main() { 
    A a; 
    B b; 

    if (a) 
     std::cout << "true\n"; 
    else 
     std::cout << "false\n"; 

    if (b) 
     std::cout << "true\n"; 
    else 
     std::cout << "false\n"; 
} 

输出:

true 
false 
+0

这并不能真正回答任何问题,这实际上应该是一个评论。 –

+1

@我不同意。 “它不。”这个问题肯定是一个有效的答案:“为什么'(var)'使用数字转换而不是布尔?”。 – verdesmarald

+0

@veredesmarald“它不是”可以是一个有效的答案,“它不在g ++上”不是(IMO),除非问题是关于g ++。也就是说,这是有用和太大,以适应评论,所以缺乏更好的选择,没有从我的投诉:) – hvd

3

如果你说的是真的,我相信你的编译器违反了标准:

(6.4节/ 4)的值在switch语句以外的语句中作为初始化声明的条件是声明变量的值在上下文中转换为bool(条款4)。如果这种转换是不合格的,那么该计划是不健全的。 [...]

(为了清楚起见,这是在第6.4节的上下文,其描述ifswitch语句。)

1

有两种used-defined implicit conversion chains

首先 - class -> bool -> no conversion

二 - class -> int -> bool

n3337 4/2

注:与给定类型的表达式会被隐式转换为其他类型的一些背景:

- 当用于if语句或迭代语句(6.4,6.5)的条件中。目标类型 是bool。

n3337 4/3

任一隐式转换的效果是一样的执行 声明和初始化,然后用临时变量作为转换的结果。

行情意味着真正

if (class_var) 

if (bool _ = class_var) 

n3337 13.3.3/1

根据这些定义,一个可行的函数F1被定义为一个更好的功能如果对于所有参数i,ICSI(F1)不是比ICSi(F2)更差的转换序列),然后

- 上下文是由用户定义的转换(参见8.5,13.3.1.5和13.3.1.6)和 标准转换序列从返回类型F1到目标类型(即,被初始化的 实体的类型)是比F235的返回类型到目标类型的标准转换序列更好的转换序列。 [示例:

struct A { 
A(); 
operator int(); 
operator double(); 
} a; 
int i = a; // a.operator int() followed by no conversion 
//is better than a.operator double() followed by 
//a conversion to int 
float x = a; //ambiguous: both possibilities require conversions, 
//and neither is better than the other 

- 结束例如

因此,编译器应该选择operator bool,因为class -> bool -> no standart conversion优于class -> int -> standard conversion to bool