首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >函数调用内部多态调用。虚函数调用

函数调用内部多态调用。虚函数调用
EN

Stack Overflow用户
提问于 2022-04-23 20:57:07
回答 1查看 57关注 0票数 -1

下面是从Derived::fn2()调用Derived::fn1(),因为fn2()不是虚拟的,所以它应该调用基类的函数。有人能解释原因吗?

代码语言:javascript
复制
#include <iostream>
using namespace std;

class Base{
    public:
    virtual void fn1()
    {
        cout<<"Base function 1"<<endl;
        this->fn2();
    }
    void fn2()
    {
        cout<<"Base function 2"<<endl;
    }
};


class Derived : public Base{
    public:
    
    void fn1()
    {
        cout<<"Derived function 1 "<<endl;
        this->fn2();
    }
    void fn2()
    {
        cout<<"Derived function 2"<<endl;
    }
};

int main()
{
    Base *b = new Derived();
    b->fn1();
}
EN

回答 1

Stack Overflow用户

发布于 2022-04-23 21:17:12

fn2()不是虚拟的,所以它应该调用基类的函数。

不,不应该。这就是为什么:

代码语言:javascript
复制
Derived d;

static_cast<Base&>(d).fn1();
// Calls Derived::fn1 through dynamic dispatching. In Derived::fn1, `this` is
// of type Derived*, so it will call Derived::fn2

// Output:
// Derived function 1
// Derived function 2

static_cast<Base&>(d).fn2();
// fn2() is not virtual, so you overloaded it. You're calling Base::fn2().

// Output:
// Base function 2
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71983565

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档