啊,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
Inner
和 Inner2
不是这样吗?如果重要的话,我正在使用 Microsoft Visual C++ 2010。
好的,感谢 John,我了解到只有指针和引用可以是协变的。这是为什么? Derived 可以转换为 Base,那么为什么具有从同一事物派生的返回类型的虚函数不将返回类型转换为基类之一呢?在我的示例中,让 (A*(new B))->blah()
返回一个真正是 的
已转换。Inner
似乎是有意义的Inner2
最佳答案
只有指针和引用可以是协变的。
关于c++ - 覆盖虚函数返回类型不同且不是协变的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6969020/