我在类模板中重载下标运算符时遇到问题。我有以下头文件来声明类模板(我仅包括相关功能):

arrayListType.h

template <class elemType>
class arrayListType {
public:
    arrayListType<elemType>& operator[](int);
    arrayListType(int size = 100);
    virtual ~arrayListType();
protected:
    elemType *list;    // array to hold the list elements
    int length;        // variable to store the length of the list
    int maxSize;       // variable to store the maximum size of the list
};

template <class elemType>
arrayListType<elemType>& arrayListType<elemType>::operator[](int index) {
    assert(0 <= index && index < length);
    return list[index];
}


我在main.cpp中有以下代码,其中felinoTipo是具有自己的属性的另一个派生类,并且工作正常。另外,我没有在前一个头文件中显示函数insertEnd,但它也可以正常工作。

main.cpp

#include "arrayListType.h"

int main() {
    arrayListType<felinoTipo> listaFelinos(20);

    felinoTipo felinoTemp1("Tigre", "Tigrillo", 1.1, 1.1);

    listaFelinos.insertEnd(felinoTemp1);

    listaFelinos[0]; //Line X

    return 0;
}


问题出现在标记为X的行中。当我注释掉该行并构建项目时,未发现任何错误。但是,当我包含那行代码时,我从类型为“ felinoTipo” main.cpp的表达式中得到了对类型为“ arrayListType&”的引用的无效初始化错误。我的主要目的是将由运算符重载函数获得的引用存储在felinoTipo基类的指针数组中,以使用虚拟函数打印出对象的属性。

知道为什么会出现这个问题吗?

最佳答案

您的操作员返回以下类型:

arrayListType<elemType>&


但是你想回来

elemType&


编译器抱怨从一个到另一个的无效转换。

您需要遵循以下原则:

template <class elemType>
class arrayListType {
public:
    typedef elemType element_type;
    element_type& operator[](int);
    const element_type& operator[](int) const; // good idea to provide const overload
....
};


然后

auto& e = listaFelinos[0];


或者,如果您没有C ++ 11,

arrayListType<felinoTipo>::element_type& e = listaFelinos[0];

10-06 05:36
查看更多