继承.为什么是这个输出

Inheritance. Why this output?

本文关键字:输出 为什么 继承      更新时间:2023-10-16

下面的程序打印3和4,但是我看不懂。有人能一步一步地解释我为什么有这个输出吗??

#include <iostream>
using namespace std;
class A{
      public: 
              int f(int x){
                        cout << x << " " << endl;
              }
};
class B : public A{
      public:
              int f(int y){
                        A :: f(y+1);
              }
};
void g(A a, B b){
     a.f(3), b.f(3);
}
int main(){
    B p; 
    B q; 
    g(p,q);
system("pause");
return 0;
}

首先,您没有虚函数,因此将调用相应类中的函数。因此,可以简单地称其为a::f(3)B::f(3)。其次,即使f 虚拟的,您也可以通过值传递g的参数,这意味着向上转换发生,因此在g中,您只需拥有A的实例和B的实例,不涉及多态性。因此输出为:

3
4