[英]c++ inheritance with method overriding
Very simple example of c++ inheritance : 非常简单的c ++继承示例:
#include <iostream>
using namespace std;
class A{
public :
virtual void print(A a){
cout<<"a"<<endl;
}
};
class B : public A {
public :
virtual void print(A a){
cout<<"a2"<<endl;
}
virtual void print(B b){
cout<<"b"<<endl;
}
};
int main(){
B b;
A &a = b;
a.print(b);
return 0;
}
Why does this output a2? 为什么输出a2? I would have expected this to be effectively the same as : b.print(b)
thanks! 我b.print(b)
预计这会有效: b.print(b)
谢谢!
Because your reference is a type A
, only the A
methods will be considered when deciding what to call. 因为您的引用是类型A
,所以在决定调用什么时只考虑A
方法。 Since print(A)
was virtual, it will actually call the method from B
that matches the signature from A
. 由于print(A)
是虚拟的,它实际上将从B
调用与A
的签名匹配的方法。
If this is confusing, consider if you had added a method foo
to B
. 如果这令人困惑,请考虑是否向B
添加了方法foo
。 What would happen if you tried to call a.foo()
? 如果你试图调用a.foo()
会发生什么? It would fail, because objects of type A
don't have a foo
method. 它会失败,因为类型A
对象没有foo
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.