我創建了一個Container類,並將new關鍵字與指針結合使用,以瞭解它如何工作以及如何使用它。運算符重載和設置值
template<typename T>
class Container {
private:
T value;
public:
Container(T value) {
this->value = value;
}
Container() {
}
virtual ~Container() {
}
T getValue() {
return value;
}
void setValue(T value) {
this->value = value;
}
void operator[](T value) {
this->value = value;
}
};
int main() {
std::vector<Container<int>*> arr(10);
for (int i = 0; i < 10; i++) {
Container<int> *a = new Container<int>;
a->setValue(i);
// a[i];
arr[i] = a;
std::cout << arr[i]->getValue() << std::endl;
delete a;
}
return 0;
}
的[]
經營者有相同的代碼setValue()
,但如果我用a->setValue(i)
並使用a[i]
它打印只是一個隨機數只打印從0至9的數字。爲什麼?
我建議你閱讀[本規範的實施參考(http://en.cppreference.com/ w/cpp/language/operators#Canonical_implementations)來重載操作符。你的[數組下標運算符重載](http://en.cppreference.com/w/cpp/language/operators#Array_subscript_operator)是錯誤的。 –
下標運算符將索引作爲參數,並且必須返回分配將更新的引用。 – Barmar