在下面的程序中,不理解答案 A::h() 和 A::h()

问题描述 投票:0回答:1

在我看来,pA是A类型的指针,但保存的是B类型的b_object的地址。sinch h()是B类中的虚函数(继承自A)并且也是重载的,因此它会隐藏该函数基类 A 的 h()。 因此,期望答案是 B::h() 但答案是 A::h(),我不知道为什么以及如何

        #include <iostream>
         using namespace std;

         class A
         {
           public:
              virtual void f(int){cout << "A::f(int)" << endl;}
              virtual void g(double){cout << "A::g(double)" << endl;}
              int h(A*){cout << "A::h()" << endl; }
         };

         class B: public A
         {
            public:
                void f(int){cout << "B::f(int)" << endl;}
                virtual int h(B*){cout << "B::h()" << endl;}
         };

         class C : public B
        {
              void g(double){cout << "C::g(double)" << endl;}
              int h(B*){cout << "C::h()" << endl; }
        };

        int main() {

                        A a_object;
                        B b_object;
                        C c_object;
                        A*pA;
                        pA = &b_object;
                        pA->h(&a_object);
                        pA->h(&b_object);
                        return 0;
                   }
c++ class oop inheritance virtual-functions
1个回答
0
投票

在类中

A
函数
h
不是虚函数

int h(A*){cout << "A::h()" << endl; }

在函数的两次调用中

h

pA->h(&a_object);
pA->h(&b_object);

由于指针

h
的类型,在类
A
中搜索函数
pA

A*pA;

由于函数

h
不是虚函数,因此指针
pA
由派生类
B
的对象的地址分配并不重要。

   pA = &b_object;

并且该函数接受指向派生类对象的指针作为参数

B

pA->h(&b_object);

因为指向派生类的指针可以隐式转换为指向其基类的指针。

© www.soinside.com 2019 - 2024. All rights reserved.