我正在构建自定义运算符,并且在向其传递参数时遇到问题。
例如
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或者我不知道。
此外,我内置了一个自定义运算符,用于打印出类测试(&lt;&lt; operator)。现在我在主程序中调用d [s]时没有得到编译错误,但是在调用cout&lt;&lt;时遇到编译错误d [s]在主程序中。运算符&lt;&lt;正在工作,因为我用简单的cout测试它&lt;&lt; d
答案 0 :(得分:1)
return test;
test
是一种类型。你不能返回一个类型。也许你的意思是:
return a;
但是你有另一个问题,因为你正在返回对局部变量的引用。当函数返回时,对象a
将被销毁(因为这是它的范围),因此引用将被悬空。
答案 1 :(得分:0)
尽管其他人已经指出了错误(悬空引用,返回类型而不是值),请注意,如果您打算覆盖[],您还应该考虑覆盖指针引用运算符(一元*)很多人都会互换使用它们。
答案 2 :(得分: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];
}