所以我正在嘗試撰寫自己的陣列模板并且一切正常,直到我嘗試創建我的類模板的 const 物件。在 main.cpp 中,我使用復制建構式創建物件并更改它,我希望它不起作用但它起作用。幫助將不勝感激:D
主檔案
# include "Array.hpp"
int main( void ) {
Array<int> l = 1;
l.setValue(5, 0);
const Array<int> abc(l);
std::cout << abc[0] << std::endl;
abc[0] = 3;
std::cout << abc[0] << std::endl;
return (0);
}
陣列.tpp
#ifndef ARRAY_TPP
# define ARRAY_TPP
# include "Array.hpp"
template<class T>
class Array {
private:
int size_;
T *array_;
public:
Array() : size_(0), array_(new T[size_]) {};
Array(int n) : size_(n), array_(new T[size_]) {};
Array(Array const& src) : size_(src.size()), array_(new T[src.size()]) {
for (int i = 0; i < src.size(); i) {
array_[i] = src[i];
}
};
Array& operator=(Array const& copy) {
size_ = copy.size();
delete[] array_;
array_ = new T[size_];
for (int i = 0; i < size_; i )
array_[i] = copy[i];
return (*this);
}
T& operator[](int n) const {
if (n < 0 || n >= size_)
throw std::out_of_range("out of range");
return (array_[n]);
}
int size(void) const { return (size_); };
void setValue(T value, int n) {
if (n < 0 || n >= size_)
throw std::out_of_range("out of range");
array_[n] = value;
}
~Array() { delete[] array_; };
};
#endif
uj5u.com熱心網友回復:
問題是這樣的:
T& operator[](int n) const { if (n < 0 || n >= size_) throw std::out_of_range("out of range"); return (array_[n]); }
因為 this 被宣告為一個const方法,所以可以在const Array. 但是,它回傳對元素的非常量參考。因為Array通過 a 存盤元素T *,所以只有該指標const在一段const Array時間內通過該指標修改元素是“好的”。
您需要兩個多載operator[]:
T& operator[](int n);
const T& operator[](int n) const;
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/517065.html
標籤:C 模板常数
上一篇:差異型別必須具有可比性嗎?
