0

I'm building custom operators and im having problems when passing parameters to them.

For example

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

Now if I wanted in my main program to do something like this

 int main(){

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

I get a bunch of errors. Is it because I need to have const somewhere or I don't know.

Also I have built in a custom operator for printing out the class test ( << operator ). Now I don't get compile error when calling d[s] in main program but I get compile error when calling cout<< d[s] in main program. The operator << is working because I tested it with simple cout<< d

4

3 回答 3

1
return test;

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

return a;

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

于 2013-05-22T10:30:14.553 回答
0
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-05-22T10:40:59.500 回答
0

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

于 2013-05-22T10:34:19.787 回答