基类指针调用派生类中虚拟的非虚基函数

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

我正在学习C++虚函数。我在基类中声明了一个非虚函数,在派生类中声明了与虚函数相同的函数。如果我使用派生对象创建基类指针并调用该函数,则它正在调用基类函数。如果该函数在基类中是非虚拟的,那怎么可能?

#include<iostream>

using namespace std;

class Vehicle{
        public:
        void steer(){
                cout<<"Steering Vehicle";
        }
};

class Car: public Vehicle{
        public:
        virtual void steer(){
                cout<<"Steering car";
        }
};
int main(){
        Vehicle* v1=new Car();
        v1->steer();
        return 0;
}

电流输出

Steering Vehicle

预期产量

Steering car

有人可以帮助我理解为什么会发生这种情况吗?

c++ polymorphism virtual-functions
1个回答
0
投票

当前的基类方法

Vechicle::steer()
实际上是非虚拟。 因此,您在派生类
Car::steer()
中提供的虚拟方法实际上并未覆盖基类方法。

要获得预期的输出,您只需将基类方法 Vehicle::steer()

标记为虚拟,如下所示:

class Vehicle{ public: //------vvvvvvv----------------->added this virtual keyword to make this virtual virtual void steer(){ cout<<"Steering Vehicle"; } };
    
© www.soinside.com 2019 - 2024. All rights reserved.