我正在构建自定义运算符,并且在向它们传递参数时遇到问题。
例如
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,还是我不知道。
此外,我还内置了一个自定义操作符( <<操作符),用于打印出类测试。现在我在主程序中调用ds时不会出现编译错误,但在主程序中调用cout<< ds时会出现编译错误。运算符<<正在工作,因为我使用简单的cout<< d对其进行了测试
发布于 2013-05-22 18:41:00
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-22 18:30:15
return test;test是一种类型。你不能返回类型。也许你的意思是:
return a;但是你还有另一个问题,因为你返回了一个局部变量的引用。当函数返回时,对象a将被销毁(因为这是它的作用域),因此引用将保持悬空。
发布于 2013-05-22 18:34:20
尽管其他人已经指出了错误(悬空引用,返回类型而不是值),但请注意,如果您打算覆盖[],您也应该考虑覆盖指针遵守运算符(一元*),因为许多人可以互换地使用它们。
https://stackoverflow.com/questions/16689423
复制相似问题