功能呼叫在多态性调用中。虚拟功能调用

发布于 2025-01-23 12:33:36 字数 707 浏览 4 评论 0原文

以下是调用derived :: fn2()来自derived :: fn1(),其中AS fn2()不是虚拟的调用基类功能。谁能解释为什么?

#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();
}

The following is calling Derived::fn2() from Derived::fn1(), where as fn2() is not virtual so it should call Base class's function. Could anyone explain why?

#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();
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

开始看清了 2025-01-30 12:33:36

fn2()不是虚拟的,因此应该调用Base类的功能。

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

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

fn2() is not virtual so it should call Base class's function.

No, it shouldn't. Here you are why:

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文