【问题标题】:class Bar { operator Foo(); }类酒吧 { 运营商 Foo(); }
【发布时间】:2011-12-30 20:10:22
【问题描述】:

这种类型的运算符重载是什么意思?

class Foo {
    Foo(int a) { ... }
};

class Bar {
    operator Foo() { return Foo(25); }
};

【问题讨论】:

    标签: c++ constructor operator-overloading


    【解决方案1】:

    这是用户定义的转换函数,将Bar的实例隐式转换为Foo。

    Bar bar;
    
    Foo foo = bar;  // bar implicitly converts into Foo.
    

    就好像你写过这样的:

    Foo foo = Foo(25);
    

    如果你有这样的转换函数,那么你可以这样调用:

    void f(Foo foo); //a function which accepts Foo
    
    f(bar); // bar implicitly converts into Foo.
    

    所以这种隐式转换有时可能是不可取的,因为它可能会导致问题,产生意想不到的结果。为避免这种情况,您可以将转换函数 explicit 设为(仅在 C++11 中):

    //valid in C++11 only
    
    class Bar {
      explicit  operator Foo() { return Foo(25); }
    };
    

    现在这两个都会出错:

    Foo foo = bar; //error
    f(bar); //error
    

    但是,以下是允许的:

    Foo foo = static_cast<Foo>(bar); //Ok
    f(static_cast<Foo>(bar)); //Ok
    

    【讨论】:

    • C++11引入使用explicit进行运算符转换?只有 AFAIR 的构造函数在 c++03 中可能是显式的,或者我记错了......
    • @Als:你是对的。在 C++03 中,只有构造函数可以是显式的。我在回答中明确表示了这一点。
    【解决方案2】:

    这是cast operator 的重载。我能找到的最好的文档是MSDN

    基本上,如果您有一个Bar,您可以将其转换为一个使用特定值构造的Foo:

    Bar b;
    Foo f = b;
    

    【讨论】:

      猜你喜欢
      • 2011-07-30
      • 2016-02-09
      • 2013-11-01
      • 2014-01-10
      • 2021-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-01
      相关资源
      最近更新 更多