【发布时间】:2013-05-15 15:43:57
【问题描述】:
我从 std::vector 继承了我的类。现在我想重载 [] 运算符。
当我尝试为我的向量分配一个新值时,例如v[0]=5, 我应该会收到消息OK。
这是我的代码(我知道,这没有意义,我只是在玩弄):
#include<vector>
#include<iostream>
class Vec : public std::vector<int> {
public:
int operator[](int);
};
int Vec::operator[](int i) {
(*this)[i] = i;
std::cout << "OK";
return 123;
}
int main() {
Vec v;
v[0]=5;
}
不幸的是,我收到以下错误:
In member function ‘int Vec::operator[](int)’:
error: lvalue required as left operand of assignmen
In function ‘int main()’:
error: lvalue required as left operand of assignment
【问题讨论】:
-
STL 容器不是以通常可继承的方式编写的;您应该通过封装将它们包装起来,而不是用于您需要/想要的操作。 stackoverflow.com/questions/2034916/…
标签: c++ vector operator-overloading