c++ - 覆盖虚函数返回类型不同且不是协变的

标签 c++ covariance virtual-functions return-type object-slicing

啊,SO回来的正是时候。

我收到一个奇怪的错误:

 'B::blah': overriding virtual function return type differs and is not covariant from 'A::blah'

这是导致问题的代码:

class A {
public:
    class Inner { };

    virtual Inner blah() = 0;
};

class B : public A {
public:
    class Inner2 : public Inner { };

    Inner2 blah() {
        return Inner2();
    }
};

我查了一下错误,根据a page I found on the Microsoft website ,类型可以协变的一种方式是如果:

the class in the return type of B::f is the same class as the class in the return type of D::f or, is an unambiguous direct or indirect base class of the class in the return type of D::f and is accessible in D

InnerInner2 不是这样吗?如果重要的话,我正在使用 Microsoft Visual C++ 2010。


好的,感谢 John,我了解到只有指针和引用可以是协变的。这是为什么? Derived 可以转换为 Base,那么为什么具有从同一事物派生的返回类型的虚函数不将返回类型转换为基类之一呢?在我的示例中,让 (A*(new B))->blah() 返回一个真正是 Inner 似乎是有意义的Inner2 已转换。

最佳答案

只有指针和引用可以是协变的。

关于c++ - 覆盖虚函数返回类型不同且不是协变的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6969020/

相关文章:

c++ - 从 C++ 调用 Python 的问题

c# - 接口(interface)的通用协方差 - "is"和 "="运算符之间奇怪的行为矛盾

c++ - 如何在 C++ 程序中查看 gdb 中的 vtable?

python - 在 pandas 中,如何计算每个列与系列的协方差?

c++ - 我明白为什么了,但是 Virtual Functions/VTables 到底是如何允许通过指针访问正确的函数的呢?

C++ Pimpl 与纯虚拟接口(interface)性能对比

c++ - 如何将自定义生成目标添加到 Visual C++ 2010 项目?

c++ - 同名的 typedef 和模板参数

c++ - "Sorted:[space]"后面没有输入号码,如何去掉空格?