简体   繁体   English

使用方法重写的c ++继承

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM