MST
星途 面试题库

面试题:C++非虚函数在继承中的调用规则

假设有一个基类Base和一个派生类Derived,Base类中有一个非虚函数print()。请写出以下代码的输出,并解释原因: ```cpp #include <iostream> class Base { public: void print() { std::cout << "Base::print()" << std::endl; } }; class Derived : public Base { public: void print() { std::cout << "Derived::print()" << std::endl; } }; int main() { Base* basePtr = new Derived(); basePtr->print(); delete basePtr; return 0; } ```
12.5万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
  1. 输出结果
    Base::print()
    
  2. 原因解释
    • 在C++ 中,非虚函数的调用是在编译期静态绑定的。
    • 当定义Base* basePtr = new Derived();时,basePtr的类型是Base*
    • 调用basePtr->print(),由于print函数在Base类中是非虚函数,编译器根据指针basePtr的静态类型(即Base*)来确定调用哪个print函数。所以调用的是Base类中的print函数,输出Base::print()。如果print函数被声明为虚函数,并且在Derived类中被重写,那么将发生动态绑定,调用的就是Derived类中的print函数,输出Derived::print()