【问题标题】:Custom operators error when passing parameters c++传递参数c ++时自定义运算符错误
【发布时间】:2013-05-17 08:47:45
【问题描述】:

我正在构建自定义运算符,但在将参数传递给它们时遇到问题。

例如

class test{
     public:
        test operator[](vector <string> s){
            test a;
            return a;
         }
}; 

现在如果我想在我的主程序中做这样的事情

 int main(){

    test d;
    vector<string> s;
    s.push_back("bla");
    d[s];
 }

我收到一堆错误。是因为我需要在某个地方有 const 还是我不知道。

我还内置了一个自定义运算符,用于打印出类测试( 对其进行了测试

【问题讨论】:

  • 请发布错误。
  • 同样,您发布的代码是fine。您能否发布失败的确切代码和错误?

标签: c++ string vector operators


【解决方案1】:
return test;

test 是一种类型。你不能返回一个类型。也许你的意思是:

return a;

但是你有另一个问题,因为你要返回一个对局部变量的引用。对象a 将在函数返回时被销毁(因为这是它的作用域),因此引用将悬空。

【讨论】:

    【解决方案2】:

    尽管其他人已经指出了错误(悬空引用,返回类型而不是值),但请注意,如果您打算覆盖 [],您还应该考虑覆盖指针引用运算符(一元 *)许多人可以互换使用它们。

    【讨论】:

      【解决方案3】:
      Code working fine using gcc compiler.
      
      #include <string>
      #include <vector>
      using namespace std;
      
      class test{
           public:
              test operator[](vector <string> s){
                  test a;
                  return a;
               }
      };
      
      int main(){
      
          test d;
          vector<string> s;
          s.push_back("bla");
          d[s];
       }
      

      【讨论】:

        猜你喜欢
        • 2013-10-21
        • 2017-11-18
        • 1970-01-01
        • 2017-04-13
        • 1970-01-01
        • 1970-01-01
        • 2014-09-15
        • 2015-05-09
        • 2014-06-02
        相关资源
        最近更新 更多