c++ - 为模板类重载 operator[] - C++

标签 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

最佳答案

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

您可能还想实现 const T& operator[] 重载。

关于c++ - 为模板类重载 operator[] - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14249461/

相关文章:

c++ - 内部/外部标题分离

c++ - 即使返回 true,CTRL+TAB 快捷方式的 Qt eventFilter 也会被进一步处理

c++ - 使用运算符重载打印单向链表

r - 重载下标运算符 "["

c++ - 为什么按此顺序评估 '--++a-​-++ +b--'?

c++ - 匹配多个组的正则表达式

c++ - 用模板替换标量失败

c++ - 关于 union 和堆分配内存的问题

C++ 重载运算符同时作为成员和函数?

c++ - 为什么在赋值运算符重载中返回引用?