2012-03-07 58 views
1
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'的含義。你能告訴我一些例子嗎?重載operator []如何工作?

+2

爲什麼第二個返回一個副本而不是一個const引用?至於const,這很容易谷歌。 – Corbin 2012-03-07 21:52:25

回答

1

對一個方法的const意味着該方法不能修改該對象。
第一個運算符[]返回一個引用到n處的元素(因此允許修改數組) - 它不能在const對象上調用。
第二個運算符[]在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,因爲它想要的功能,能夠讀取該數組,但不改變參數的情況下它。

2

成員函數具有隱式參數this,尾隨const用於函數重載解析。你可以這樣想:

void Array::function() -> void function(Array* this) 

void Array::function() const -> void function(Array const* this)