重写虚函数返回类型不同并且不是协变的
啊,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我在 Microsoft 网站上找到的页面,类型可以协变的方式之一是:
B::f 返回类型中的类与 D::f 返回类型中的类是同一类,或者是 D::f 返回类型中类的明确直接或间接基类: :f 并且可以在 D 中访问
Inner
和 Inner2
不是这样吗?如果有必要的话,我正在使用 Microsoft Visual C++ 2010。
好的,感谢约翰,我了解到只有指针和引用可以是协变的。这是为什么? Derived 可以强制转换为 Base,那么为什么具有从同一事物派生的返回类型的虚拟函数不将返回类型强制转换为基类之一呢?在我的示例中,让 (A*(new B))->blah()
返回一个实际上是 Inner
似乎是有意义的>Inner2 已被铸造。
Ah, SO came back just in time.
I am getting a strange error:
'B::blah': overriding virtual function return type differs and is not covariant from 'A::blah'
Here is the code causing the problem:
class A {
public:
class Inner { };
virtual Inner blah() = 0;
};
class B : public A {
public:
class Inner2 : public Inner { };
Inner2 blah() {
return Inner2();
}
};
I looked up the error, and according to a page I found on the Microsoft website, one of the ways types can be covariant is if:
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
Is that not the case with Inner
and Inner2
? I am using Microsoft Visual C++ 2010 if it matters.
OK, so thanks to John I learned that only pointers and references can be covariant. Why is that? A Derived can be cast to a Base, so why don't virtual functions with return types that are derived from the same thing just cast the return type to the one of the base class? In my example, it seems like it would make sense to have (A*(new B))->blah()
return a Inner
that is really an Inner2
that has been cast up.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(6)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
只有指针和引用可以是协变的。
Only pointers and references can be covariant.