2013-01-10 230 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