Qt:关于C++中虚函数的动态绑定

一、测试代码如下:

#include <iostream>
using namespace std;

class Base
{
    
    
public:
    virtual void out() {
    
     cout << "Base::out()" << endl; }
    void in() {
    
     cout << "Base::in()" << endl; }
};

class Derived : public Base
{
    
    
public:
    virtual void out() {
    
     cout << "Derived::out()" << endl; }
    void in() {
    
     cout << "Derived::in()" << endl; }
};

int main()
{
    
    
    Base* base = new Derived;
    base->out(); // Derived::out()
    base->in();  // Base::in()
    return 0;
}

二、输出结果:
在这里插入图片描述
三、结论
由于out()函数是虚函数,因此在主函数main()中调用时,发生了动态绑定:尽管是父类的指针,但输出的却是子类对象,所以输出的是Derived::out()。动态绑定的结果是,父类指针调用了子类的实现,这就是多态。而对于in()函数,由于没有virtual修饰,不会发生动态绑定,因此只是输出的父类结果Base::in()。

猜你喜欢

转载自blog.csdn.net/qq_27538633/article/details/113733548
今日推荐