【问题标题】:C++ - overloading [] operatorC++ - 重载 [] 运算符
【发布时间】:2016-04-08 04:34:09
【问题描述】:

我有一个模板类数组:

template <class T=int, int SIZE=10>
class Array {
    T TheArray[SIZE];
public:
    void Initialize() {
        for (int idx=0; idx < SIZE; idx++) {
            TheArray[idx] = T();
        }
    }

    T& operator [](int idx) {
        return TheArray[idx];
    }

    T operator [](int idx) const {
        return TheArray[idx];
    }
}

我对运算符[] 重载有一些疑问(我在网上找到了这个例子)。

我了解T&amp; operator [](int idx) 返回对索引为idx 的数组值的引用,而T operator [](int idx) const 返回其值。 但是,我不确定在哪种情况下使用 [] 运算符会返回引用或值。

另外,如果我更改 T operator [](int idx) const -> T operator [](int idx),编译器会抱怨。这是为什么? 我可以理解编译器抱怨是因为只有返回类型不同,但是为什么在添加const 时它不抱怨?这只意味着没有任何类内部被修改,对吧?

我尝试调试这个小的主要实现:

int main() {
    int val;
    Array<> intArray;

    intArray.Initialize();
    val = intArray[1];
    printf("%d", intArray[1]);
    intArray[1] = 5;
}

并且每次调用T&amp; operator [](int idx)。为什么?

提前致谢。

【问题讨论】:

  • 附带说明,比起initialize 之类的函数,更喜欢合适的构造函数。 C++ 为您提供了一个完美的对象初始化工具,它被称为构造函数。

标签: c++ operator-overloading overloading operator-keyword


【解决方案1】:

operator[] 重载将根据您调用它的对象的const 限定来选择。

Array<> intArray;
intArray[1]; //calls T& operator[]

const Array<> constArray;
constArray[1]; //calls T operator[]

如果从T operator[] 中删除const,则会出现错误,因为成员函数不能具有相同的const-qualification 和参数,因为无法在它们之间进行选择。

【讨论】:

    【解决方案2】:

    首先,将[] 视为调用this-&gt;operator[] 的语法糖。

    如果thisconst 指针,则将调用const 版本,否则将调用非const 版本。

    继续前进,您应该使用const T&amp; operator [](int idx) const {,即让const 版本返回const 引用。这将节省进行深拷贝的开销。

    最后,函数的const-ness 其签名的一部分。这允许您基于const-ness 进行重载。否则你无法拥有operator[] 的两个版本。

    【讨论】:

    • 我什至会在这里调用返回一个临时而不是 const 引用一个设计气味/错误,因为它会导致不一致,即:why cant I use const arguments in memcpy? 应该将自己定位在标准库上以防止出现意外行为std::vector 返回一个常量引用。
    猜你喜欢
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    • 2012-06-02
    • 2014-01-14
    • 2013-03-23
    • 2013-12-03
    • 2013-06-07
    相关资源
    最近更新 更多