C++ 'overloading' if() 语句
C++ 'overloading' the if() statement
是否有可能改变if()
的行为,使:
class Foo {
int x;
};
Foo foo;
if(foo)
仅在x
的值不是零的情况下进行?还是…
将显式用户定义的类型转换为int是否可行?还是…
最好是做一些像if(foo.getX())
?
您可以通过定义operator bool()
将对象转换为布尔值:
explicit operator bool() const
{
return foo.getX();
}
explicit
关键字阻止从Foo
到bool
的隐式转换。例如,如果您不小心将foo
放入像foo + 1
这样的算术表达式中,如果您将operator bool()
声明为explicit
,编译器可以检测到此错误,否则foo
将被转换为bool
,即使不是有意的。
通常形式的成员函数
operator TypeName()
(带有可选的explicit
和const
限定符)是转换操作符。它允许您将类强制转换为TypeName
指定的任何类型。在另一个方向上,带一个参数的构造函数允许您将任何类型强制转换为类:
class Foo {
Foo(int x); // convert int to Foo
operator bool() const; // convert Foo to bool
int x;
};
这为你的类定义了隐式转换。如果可能的话,编译器会尝试应用这些转换(就像它对内置数据类型所做的那样,例如5 + 1.0
)。您可以将它们声明为explicit
以抑制不需要的隐式转换。
可以定义一个操作符将对象转换为bool
class Foo
{
int x;
public:
operator bool() const
{
return x > 0;
}
};
但是这可能会产生意想不到的后果,因为当您不希望进行转换时,会隐式转换到bool
。例如
int x = 42 + Foo();
c++ 11通过允许您将转换操作符声明为explicit
来解决这个问题,这样只允许在特定上下文中(例如在if
语句中)进行隐式转换。
explicit operator bool() const // allowed in C++11
现在int x = 42 + Foo(); // error, no implicit conversion to bool
int x = 42 + static_cast<bool>(Foo()); // OK, explicit conversion is allowed
相关文章:
- 我的简单if-else语句是如何无法访问的代码
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- 为什么是0;C++中的有效语句
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 是否可以使用if constexpr删除控制流语句
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 我似乎对if/else的基本语句有问题:/
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- If语句在c++中被忽略
- 比较if语句中的数组值和int值
- 以在Qt中的IF语句中设置时间延迟
- Craps游戏问题,忽略if语句
- "类模板示例<int>;"语句对 C++11 是什么意思?
- 如何编写一个使用n倍三元条件语句的C++布尔函数
- c++:定义if语句中的模板
- C++ 'overloading' if() 语句