【问题标题】:function call operator in class or method?类或方法中的函数调用运算符?
【发布时间】:2022-03-22 16:05:55
【问题描述】:
class foo
{
public:
    struct bar
    {
        bar() {}
        int bar_var;
    };

    operator std::vector<bar>() {
        return m_list;
    }

private:
    std::vector<bar> m_list;
    int foo_var;
};

这里定义了一个类foo,这里的语义“运算符std:vector()”是什么意思?我不认为它是一个重载的函数调用运算符。

用上面的代码编译就可以了

【问题讨论】:

    标签: c++ c++11


    【解决方案1】:

    这里的语义“运算符 std:vector()”是什么意思?

    它表示一个conversion operator,它允许您在需要std::vector&lt;bar&gt; 的地方使用foo 对象。转换运算符是一种特殊的成员函数,可将 类类型 的值转换为其他类型的值。

    例如,假设我们有一个名为func 的函数,它将std::vector&lt;foo::bar&gt; 作为其唯一参数。现在, 您甚至可以通过传递foo 对象而不是传递std::vector&lt;foo::bar&gt; 来调用此函数,如下所示:

    //--------vvvvvvvvvvvvvvvvvvvvv----------> expects std::vector<foo::bar> 
    void func(std::vector<foo::bar> m)
    {
        std::cout<<"func called"<<std::endl;
    }
    int main()
    {
        foo fObject;
    //-------vvvvvvv---->passing a foo object which implicitly uses the conversion operator    
        func(fObject); 
        
    }
    

    Working demo

    在上面的演示中,func 需要 std::vector&lt;foo::bar&gt;。但是我们传递了fObject,它是foo 类型的对象,因此使用您提供的转换运算符将fObject 进行隐式转换std::vector&lt;foo::bar&gt;

    【讨论】:

      【解决方案2】:

      这是一个conversion function。在您的示例中,如果在预期 std::vector&lt;bar&gt; 的上下文中使用过 foo ,它将很高兴地调用该函数。更典型的用例可能类似于

      class MyCustomNumberType {
      private:
        // Super secret number arithmetic stuff.
      public:
        operator double() {
          // Convert to a double and return here...
        }
      }
      
      MyCustomNumberType foo = /* more complicated math ... */;
      double bar = foo + 1.0;
      

      【讨论】:

        猜你喜欢
        • 2020-05-12
        • 2018-07-05
        • 1970-01-01
        • 1970-01-01
        • 2021-05-17
        • 2017-06-12
        • 2020-02-19
        • 1970-01-01
        • 2023-03-31
        相关资源
        最近更新 更多