为什么编译没有错误?(返回不对所述返回类型进行子类化的类型)
Why does this compile without errors? (Returning a type that doesn't subclass the stated returned type)
我继承了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 {
};
};
inexistent_element
还没有继承T
,所以不应该编译。但它会编译。此外,我非常确信C++不应该允许我通过非常量引用传递内联创建的对象。
我正在使用Code::Blocks IDE和MinGW gcc编译器。我想知道为什么会编译。
您从未实例化过成员函数operator[]
。我怎么知道的?这是私人的。
请注意,实例化类不会自动实例化其成员函数([temp.inst]/1):
类模板专门化的隐式实例化导致声明的隐式实例化,但不是类成员函数的定义或默认参数,成员类、作用域成员枚举、静态数据成员和成员模板;
显然,正如其他人所指出的,您从未实际实例化过operator[]
;编译器不需要诊断没有法律依据的情况实例化是可能的,不同的编译器也或多或少在这方面具有侵略性。(如果没有实例化;g++将诊断大多数没有法律依据的情况实例化。)
但当然,你的功能也可能有法律上的实例化。inexisting_element
可能没有基类,但T
可能有通过const引用获取inexisting_element
的非显式构造函数,因此编译器在知道CCD_ 10之前不能合法地拒绝该代码;即函数已实例化。
相关文章:
- 从父类方法返回子类对象
- C ++类型特征:确保子类实现方法
- 文本冒险游戏 - 如何区分一种项目类型与另一种项目类型以及如何构建项目类/子类
- 将C++子类成员函数(虚拟实现)传递给 C 类型函数指针
- 将成员函数的返回类型引用到C++中的自定义类
- 返回具体子类实例的 C++ 虚拟类函数
- 当函数返回类型为父类时,如何返回子类的对象?
- 如何使函数返回由子类定义的值?C++
- 为什么+运算符重载返回类型是类类型而不是整数
- 使用另一个类作为返回类型的类
- 非标量类型子类错误
- 当返回类型为类时,带有尾随返回类型的 GCC 属性警告
- 为什么编译没有错误?(返回不对所述返回类型进行子类化的类型)
- 返回类型是类中的一个变量
- 返回指向子类的指针的好方法
- 模板类的不同返回类型取决于类的形参
- 重写子类中的返回类型
- 如何返回“set”方法的子类类型
- 可以对返回子类类型的基类进行赋值操作符吗?
- 如何使子类上的操作符返回子类类型?