虚函数的返回类型不同 [英] Differing return type for virtual functions
本文介绍了虚函数的返回类型不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
虚拟函数的返回类型应该与基类或协变中的类型相同.但是为什么我们有这个限制?
A virtual function's return type should be the same type that is in base class, or covariant. But why do we have this restriction?
推荐答案
由于胡说八道:
struct foo
{
virtual int get() const { return 0; }
};
struct bar : foo
{
std::string get() const { return "this certainly isn't an int"; }
};
int main()
{
bar b;
foo* f = &b;
int result = f->get(); // int, right? ...right?
}
让派生类返回完全不相关的内容是不明智的.
It isn't sensible to have a derived class return something completely unrelated.
这篇关于虚函数的返回类型不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文