[英]How does overloading operator[] work?
struct rowDisplayPolicy
{
static std::string seperator() { return ", "; }
};
struct columnDisplayPolicy
{
static std::string seperator() { return "\n "; }
};
template <typename T, int Size, typename DisplayPolicy>
class Array {
public:
Array() : pArray(new T[Size]) {}
Array(T* pT) : pArray(new T[Size])
{
for(int i=0; i<Size; ++i)
*(pArray + i) = *(pT + i);
}
~Array() { delete [] pArray; }
T& operator[](int n)
{
if(n<0 || Size<=n) throw std::Exception("index out of range");
return *(pArray+n);
}
T operator[](int n) const
{
if(n<0 || Size<=n) throw std::Exception("index out of range");
return *(pArray+n);
}
void display() const
{
std::cout << "\n ";
for(int i=0; i<Size-1; ++i)
std::cout << *(pArray+i) << DisplayPolicy::seperator();
std::cout << *(pArray+Size-1) << "\n";
}
private:
Array(const Array<T,Size,DisplayPolicy>&); // make public impl. Later
Array<T,Size,DisplayPolicy>& operator=(const Array<T,Size,DisplayPolicy>&); // ditto
T* pArray;
};
我有一個問題,為什么operator []重載兩種不同的方式。 他們之間有什么區別。 我不清楚'function()const'的含義。 你能告訴我一些例子嗎?
成員函數有一個隱含參數this
,尾隨const
用於函數重載解析。 你可以這樣想:
void Array::function() -> void function( Array* this )
void Array::function() const -> void function( Array const* this )
方法上的const意味着該方法不允許修改對象。
第一個operator []返回對 n處元素的引用 (因此允許修改數組) - 它不能在const對象上調用。
第二個operator []在n處返回元素的副本 。 它不會修改數組 - 並且可以在const對象上調用。 例如:
Array<int, 10> my_array1();
int test1 = my_array1[0]; // Calls first operator[]
const Array<int, 10> my_array2();
int test2 = my_array2[0]; // Calls second operator equals
這通常適用於將數組作為參數傳遞給函數的上下文,其中它可能被限定為const,因為它希望函數能夠讀取數組但不能更改它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.