模板操作符[]=

Template Operator []=

本文关键字:操作符      更新时间:2023-10-16

作为练习,我正在制作一个模板数组类,我想执行以下操作:

Array<int> a[5];
a[4] = 2;

我怎么写这样的东西?
我试过:

template<class T> class Array{
...
T operator[(const int loc)]=(const T temp);

您编写一个operator [],它返回对该元素的引用。作为一个引用,它可以通过=被赋值。

template <typename T>
class Array {
    …
    T& operator [](unsigned int const loc) {
        …
    }
};

(参数中的const不常用,但可以在函数定义中使用它-然而,在其声明中它没有意义。)

您通常需要另一个版本操作符是const,因此您仍然可以const数组读取值:

Array<int> x;
Array<int> const& y = x;
std::cout << y[0]; // Won’t compile!

要编译最后一行,请将以下代码添加到您的类中:

T const& operator [](unsigned int const loc) const {
    …
}

注意,返回值和函数本身都被标记为const