2013-01-10 234 views
0

剛剛寫了一個模板數組類的代碼(我知道它還沒有完成),並試圖記住如何重載運算符(同時沒有特別的困難...)。重載運算符[]爲模板類C++

無論如何,當考慮如何實現operator[]我想知道如果索引超出數組邊界會發生什麼......我敢肯定,我不可能返回一個NULL(因爲返回類型),對嗎?如果是的話,如果指數超出邊界,我應該返回什麼?

這裏的代碼,其中大部分是多餘的,我的問題,但它可能會幫助任何人誰谷歌的運營商超載,所以我張貼的完整代碼...

#ifndef __MYARRAY_H 
#define __MYARRAY_H 

#include <iostream> 
using namespace std; 

template <class T> 
class MyArray 
{ 
    int phisicalSize, logicalSize; 
    char printDelimiter; 
    T* arr; 

public: 
    MyArray(int size=10, char printDelimiter=' '); 
    MyArray(const MyArray& other); 
    ~MyArray() {delete []arr;} 

    const MyArray& operator=(const MyArray& other); 
    const MyArray& operator+=(const T& newVal); 

    T& operator[](int index); 

    friend ostream& operator<<(ostream& os, const MyArray& ma) 
    { 
     for(int i=0; i<ma.logicalSize; i++) 
      os << ma.arr[i] << ma.printDelimiter; 
     return os; 
    } 
}; 

template <class T> 
T& MyArray<T>::operator[](int index) 
{ 
    if (index < 0 || index > logicalSize) 
    { 
     //do what??? 
    } 

    return arr[index]; 
} 

template <class T> 
const MyArray<T>& MyArray<T>::operator+=(const T& newVal) 
{ 
    if (logicalSize < phisicalSize) 
    { 
     arr[logicalSize] = newVal; 
     logicalSize++; 
    } 

    return *this; 
} 

template <class T> 
const MyArray<T>& MyArray<T>::operator=(const MyArray<T>& other) 
{ 
    if (this != &other) 
    { 
     delete []arr; 
     phisicalSize = other.phisicalSize; 
     logicalSize = other.logicalSize; 
     printDelimiter = other.printDelimiter; 
     arr = new T[phisicalSize]; 

     for(int i=0; i<logicalSize; i++) 
      arr[i] = other.arr[i]; 
    } 

    return *this; 
} 

template <class T> 
MyArray<T>::MyArray(const MyArray& other) : arr(NULL) 
{ 
    *this = other; 
} 

template <class T> 
MyArray<T>::MyArray(int size, char printDelimiter) : phisicalSize(size), logicalSize(0), printDelimiter(printDelimiter) 
{ 
    arr = new T[phisicalSize]; 
} 

#endif 
+1

你應該-at most _assert_,它是一個錯誤,以索引一個數組超越其邊界... –

+4

'__MYARRAY_H'是一個[保留](http://stackoverflow.com/questions/228783/what-are-關於使用下劃線的ac標識符)標識符。 – chris

+2

你可能會拋出異常。 – brain

回答

6

operator[]一般不無邊界檢查。大多數具有範圍的標準容器都使用單獨的功能,at(),這是範圍檢查並引發std::out_of_range異常。

您可能還想實現const T& operator[]過載。

+0

剛纔iplemented'const T&operator []':)關於異常 - 我不知道我想使用異常...雖然它是一個很好的解決方案。 – omi