具有引用返回类型的重写方法上的协变返回类型无效
Invalid covariant return type on overridden methods with reference return types
我正在使用 PIMPL 习语实现继承。我有两个类,例如:
// In Base.h
class Base
{
virtual BaseImpl& getImpl() const;
private:
std::unique_ptr<BaseImpl> _pImpl;
};
// In Derived.h
class Derived : public Base
{
DerivedImpl& getImpl() const /* override */;
};
// In BaseImpl.h
class BaseImpl { ... };
// In DerivedImpl.h
class DerivedImpl : public BaseImpl { ... };
现在,如果我取消注释上面的override
关键字,编译器会抱怨协变返回类型在覆盖getImpl()
时无效。
由于DerivedImpl
派生自BaseImpl
并且我返回引用,那么这里的协方差问题在哪里?
注意:此代码示例是自愿不排序的,类位于独立的文件中。问题仅与override
关键字有关。代码在没有它的情况下编译。
由于 DerivedImpl 派生自 BaseImpl,而我返回引用,这里的协方差问题在哪里?
问题是编译器无法预测DerivedImpl
是否会从BaseImpl
派生。它还不知道这一点,因为在声明被覆盖的函数时尚未定义DerivedImpl
。这可以通过重新排序定义来解决:
class BaseImpl { };
class DerivedImpl : public BaseImpl { };
class Derived : public Base
{
DerivedImpl& getImpl() const override ;
};
如果不能使返回类型的定义在函数声明点可见,则不能使用协变返回类型。
相关文章:
- 如何获取std::result_of函数的返回类型
- 奇怪的结构&GCC&clang(void*返回类型)
- 如何建立使用模板函数的lambda函数的尾部返回类型
- 为什么与常规GCC不同,即使有"学究性错误",MinGW-GCC也能容忍丢失的返回类型
- 自动返回类型匹配无效
- 具有引用返回类型的重写方法上的协变返回类型无效
- 对"无效的抽象返回类型"进行故障排除
- 无效的协变返回类型,嵌套类C
- 错误:返回类型 'class Polar' 不完整,无效使用类型 'polar'
- 返回并强制转换数组指针(错误:数组下标的类型..无效)
- 无效的协变返回类型
- 协变返回类型无效的转换错误
- 无效的协变返回类型错误
- 为"虚拟无效"指定的冲突返回类型
- 函数常量返回类型:类型引用的初始化无效
- 具有基类的CRTP试图获取派生类成员的返回类型:不完整类型的使用无效
- 嵌套迭代器和接口中的"无效协变返回类型"错误
- 嵌套类中的"无效协变返回类型"错误,该方法返回基于模板的对象
- 抽象类:成员函数virtual..的抽象返回类型无效
- 使用虚函数协变返回类型的c++无效转换错误