2016-02-13 56 views
1

我想爲微控制器創建一個更小的向量類。C++數組像類元素定義

在正常向量類,你可以這樣做:

myvector[1] = 100; 

怎麼可能實現一類這樣的作業嗎?

我嘗試這樣做:

template<typename T> 
class Vector 
{ 
private: 
    T* content; 
public: 
    T* operator[](unsigned int); 
}; 
template <typename T> 
T* Vector::operator[](unsigned int i) 
{ 
    return &content[i]; 
} 

但是,拋出的錯誤,也不會是一個很好的解決方案。

那我該怎麼辦?

回答

2

在上面顯示的情況下,您正在返回一個指向該值的指針,這可能是您爲什麼遇到困難。考慮返回一個參考,而不是:

T& operator[](unsigned int); 
+0

&內容[我]不能用它,我不知道爲什麼。 Visual Studio說「引用非const的初始值必須是一個左值」 – DLCom

+0

啊,明白了。要定義參考,您不需要&運算符。 你可以這樣做: T&myref = content [i]; – DLCom

+0

@DLCom你只是'在你修改過的T&operator [](unsigned int);'中返回content [i];'我也建議用['std :: size_t'](http://en.cppreference.com/w/cpp/types/size_t)替換'unsigned int'。 – vsoftco