[英]Assign a value to a specific element in a custom vector class. As a[5] = 3 C++
[英]I'm creating my own array class, using the vector class. How do I allow a user to assign each element individually?
我有一個非常簡單的數組類,基於vector類:
class myarray{
private:
vector<double> data_;
int size_;
public:
/// Constructor that allocates the memory
myarray(const int& nx): size_(nx) {
data_.resize(size_);
}
blah, blah, blah...
我希望用戶能夠單獨分配myarray的每個元素。 例如,在聲明對象之后
myarray A(10);
我希望用戶能夠執行以下操作:
A(0) = 1;
A(1) = 2;
等等。我該怎么辦?
為operator()(size_t)
提供幾個重載:
int& operator()(std::size_t i) { return data_[i]; }
const int& operator()(std::size_t i) const { return data_[i]; }
第一個版本允許您讀取和寫入myarray
的可變實例的元素。 第二個允許你讀取myarray
的const
實例的元素(或通過const
引用或指向const
訪問)。
注意:嚴格來說,索引的正確類型是std::vector<double>::size_type
。 這通常與std::size_t
相同,但如果使用自定義分配器,則可能不同。
提供重載的operator()(int i)
函數。
int operator()(int i ) { return data_[i]; }
這是否是正確的做法,這是你的號召。
如果您希望能夠使用:
A(0) = 5;
更改函數以返回引用。 事實上,也有一個const
的過載。
int& operator()(int i ) { return data_[i]; }
int const& operator()(int i ) const { return data_[i]; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.