C ++“重载" if()语句 [英] C++ 'overloading' the if() statement

查看:98
本文介绍了C ++“重载" if()语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以更改if()的行为,以便:

Is it possible to change the behavior of if() so that:

class Foo {
    int x;
};

Foo foo;
if(foo)

仅当x的值不是零时,

才会继续?或...

only proceeds if the value of x is something other than zero? or...

将用户定义的类型显式转换为int work/是否合适?或...

Would an explicit user-defined type conversion to int work/would that be an appropriate approach? or...

最好做类似if(foo.getX())的事情吗?

推荐答案

您可以通过定义operator bool()将对象转换为布尔值:

You can convert your object to a boolean value by defining operator bool():

explicit operator bool() const 
{ 
    return foo.getX(); 
}

explicit关键字可防止从Foobool的隐式转换.例如,如果您不小心将foo放在类似foo + 1的算术表达式中,则如果将operator bool()声明为explicit,则编译器可能会检测到此错误,否则即使不是,foo也将转换为bool.

The explicit keyword prevents implicit conversions from Foo to bool. For example, if you accidentally put foo in an arithmetic expression like foo + 1, the compiler could detect this error if you declare operator bool() as explicit, otherwise foo will be converted to bool even if not intended.

一般来说,形式为成员函数

operator TypeName()

(带有可选的explicitconst限定词)是转换运算符.它允许您将类强制转换为TypeName指定的任何类型.另一方面,带有一个参数的构造函数允许您将任何类型强制转换为您的类:

(with optional explicit and const qualifier) are conversion operators. It allows you to cast your class to any type specified by TypeName. In the other direction, constructors with one argument allow you to cast any type to your class:

class Foo {
  Foo(int x);    // convert int to Foo
  operator bool() const;  // convert Foo to bool
  int x;
};

这为您的课程定义了隐式转换.编译器会尽可能尝试应用这些转换(例如对内置数据类型,例如5 + 1.0所做的操作).您可以将它们声明为explicit以禁止不必要的隐式转换.

This defines implicit conversions for your class. The compiler tries to apply these conversions if possible (like what it does for built-in data types, e.g. 5 + 1.0). You can declare them to be explicit to suppress unwanted implicit conversions.

这篇关于C ++“重载" if()语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆