简体   繁体   English

如何从类对象返回值?

[英]How can I return a value from a class object?

Is it possible to have a class object return a true/false value, so I can do something like this: 是否有可能让类对象返回true / false值,所以我可以这样做:

MyClass a;
...
if (a)
    do_something();

I can accomplish (almost) what I want by overloading the ! 我可以通过重载来完成(几乎)我想要的东西! operator: 运营商:

class MyClass {
    ...
    bool operator!() const { return !some_condition; };
    ...
}

main()
    MyClass a;
    ...
    if (!a)
        do_something_different();

but I haven't found a way to overload what would be the "empty" operator. 但我还没有找到一种方法来重载什么是“空”运算符。 Of course, using the == operator to check for true/false is also possible, and is in fact what I have been doing so far. 当然,使用==运算符检查true / false也是可能的,事实上我到目前为止一直在做。

Overload the void * cast operator: 重载void * cast操作符:

operator void * () const { return some_condition; };

this is how streams work, allowing you to say: 这就是流的工作原理,让你说:

if ( cin ) {
   // stream is OK
}

The use of void * rather than bool prevents the cast being used by mistake in some contexts, such as arithmetic, where it would not be desirable. 使用void *而不是bool可以防止在某些情况下错误地使用强制转换,例如算术,这是不可取的。 Unless, you want to use it in those contexts, of course. 当然,除非您想在这些环境中使用它。

The obvious solution – providing an implicit conversion to bool via operator bool – is a bad idea. 显而易见的解决方案 - 通过operator bool提供对bool的隐式转换 - 是一个坏主意。

That's why the standard library uses operator void* as shown in Neil's answer. 这就是标准库使用operator void* ,如Neil的回答所示。

However, it's worth pointing out that even this solution has flaws and is therefore no longer considered safe. 然而,值得指出的是,即使这种解决方案也存在缺陷,因此不再被认为是安全的。 Unfortunately, coming up with a better solution isn't trivial … 不幸的是,想出一个更好的解决方案并非易事......

There's an article over at Artima that describes the safe bool idiom . 在Artima上有一篇文章描述了安全的bool成语 For a real library, this is definitely the way to go, since it offers the most robust interface that is hardest to use wrong. 对于一个真正的库,这绝对是要走的路,因为它提供了最难以使用的最强大的界面。

Weird, no one has mentioned the safe bool idiom so far. 很奇怪,到目前为止还没有人提到过安全的bool成语 All the other solutions described so far have drawbacks (which you might or might not care about), all those approaches are described in the article. 到目前为止所描述的所有其他解决方案都有缺点(您可能会或可能不会关心),所有这些方法都在本文中进行了描述。 In a nutshell, the safe bool idiom goes something like this: 简而言之,安全bool成语是这样的:

  class Testable {
    typedef void (Testable::*bool_type)() const;
    void this_type_does_not_support_comparisons() const {}
  public:
    operator bool_type() const {
      return /* condition here */ ? 
        &Testable::this_type_does_not_support_comparisons  // true value
        : 0; // false value
    }
  };

尝试重载(bool)运算符:

operator bool() { /* ... */ }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM