重载operator []以获取模板类-c ++

时间:2013-01-10 01:33:08

标签: c++ operator-overloading

刚刚写了一个模板数组类的代码(我知道它还没有完成),并试图记住如何重载运算符(同时没有特别的困难......)。

无论如何,在考虑如何实现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 个答案:

答案 0 :(得分:6)

operator[]通常不进行边界检查。大多数可以具有范围的标准容器都使用单独的函数at(),该函数进行范围检查并抛出std::out_of_range异常。

您可能也希望实现const T& operator[]重载。

相关问题