为什么这个编译没有错误?(返回不包含所声明的返回类型的类型)

use*_*201 1 c++ inheritance

我继承std::list了允许[]运算符'伪随机访问' .

#include <list>
template <typename T>
class rlist : public std::list<T> {
    T& operator[](int index){
        typename std::list<T>::iterator iterator;
        int pos;
        for (iterator = this->begin(), pos = 0; iterator != this->end(); iterator++, pos++)
            if (pos == index)
                return *iterator;
        return inexistent_element();
    }

    class inexistent_element {

    };
};
Run Code Online (Sandbox Code Playgroud)

inexistent_element还没有继承T,所以这不应该编译.但它编译.另外我很确定C++不应该允许我通过非const引用传递一个内联创建的对象.

我正在使用Code :: Blocks IDE和MinGW gcc编译器.我想知道为什么这会编译.

Col*_*mbo 5

成员函数operator[]从未被您实例化.我怎么知道的?这是私人的.

请注意,实例化类不会自动实例化其成员函数([temp.inst]/1):

类模板特化的隐式实例化导致类成员函数,成员类,作用域成员枚举,静态数据成员和成员模板的声明的隐式实例化,而不是定义或默认参数的隐式实例化.

  • @ user3834459我刚才说你无法实例化(使用过)它,因为它是私有的.如果它是公开的你可以使用它,不是吗? (2认同)