C++ 'overloading' the if() statement

前端 未结 2 1726
长情又很酷
长情又很酷 2021-02-19 20:14

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

class Foo {
    int x;
};

Foo foo;
if(foo)

only proceeds if the value of <

2条回答
  •  孤独总比滥情好
    2021-02-19 20:30

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

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

    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.

    In general, member functions of the form

    operator 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;
    };
    

    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.

提交回复
热议问题