A、基类的成员函数B、派生类的成员函数C、不确定D、随机调用这里没有写清楚是不是虚函数,如何解决?

当基类指针指向派生类对象时,利用基类指针调用派生类中与基类同名但被派生类重写后的成员函数时,调用的是( )。
A、基类的成员函数
B、派生类的成员函数
C、不确定
D、随机调用
这里没有写清楚是不是虚函数,是不是应该存在不确定性?

你这么一说,我心理也没底了。到底是故意的,还是出题失误呢?

当基类指针指向派生类对象时,利用基类指针调用派生类中与基类同名但被派生类重写后的成员函数时,调用的是派生类的成员函数。因为在派生类中重新定义了该成员函数覆盖了基类中的同名函数,基类指针指向的是派生类的对象,调用的是派生类的成员函数。如果要调用基类的同名函数,可以使用作用域解析运算符::来指定。
所以选择B
你可以自己试一下


#include <iostream>

using namespace std;

class Base {
public:
    virtual void print() {
        cout << "This is the Base class" << endl;
    }
};

class Derived : public Base {
public:
    void print() {
        cout << "This is the Derived class" << endl;
    }
};

int main() {
    Base* ptrBase = new Base;
    Derived* ptrDerived = new Derived;

    ptrBase->print(); // This is the Base class
    ptrDerived->print(); // This is the Derived class

    ptrBase = ptrDerived;
    ptrBase->print(); // This is the Derived class

    delete ptrBase;
    delete ptrDerived;

    return 0;
}