【问题标题】:Understanding virtual functions and destructors calling [duplicate]了解虚函数和析构函数调用[重复]
【发布时间】:2019-06-07 16:09:38
【问题描述】:

我对两个代码块感到困惑。我会写下我的期望和结果。所以:

我有这样的代码:

#include <iostream>

class Base {

    void method() {std::cout << "from Base" << std::endl;}
public:
    virtual ~Base() {method();}
    void baseMethod() 
    {
        method();
    }
};

class A : public Base {
    void method() {std::cout << "from A" << std::endl;}
public:
    ~A() {
        std::cout<<"Destructor a" << std::endl;
        method();
    }
    void baseMethod() 
    {
        std::cout<<"Called A" << std::endl;
        method();
    }
};

int main(void) {
    Base* base = new A;
    base->baseMethod();
    delete base;
    return 0;
}

并在终端输出:

from Base
Destructor a
from A
from Base

问题是,method() 不是虚拟的。例如,在main函数中调用baseMethod(),调用base->baseMethod()调用基类baseMethod,在baseMethod()内部,调用method()。由于 method() 不是虚拟的,它调用基类方法并打印“From Base”。没关系。

但是.. 用线删除基点时

delete Base;

由于基类析构函数是虚拟的,它调用派生类析构函数~A()。在这个析构函数中,method() 调用。但是通过查看输出,这个method() 调用,调用A 类的method() 并从A 打印到屏幕。但是 method() 不是 virtual 。由基类指针调用的析构函数,很快,我期待析构函数A中的B,但它打印From A。它是怎么回事? .

我的期望:

from Base
Destructor a
from Base
from Base

当我将 virtual 添加到这一行时:

class Base {

    virtual void method() {std::cout << "from Base" << std::endl;}

输出是:

from A
Destructor a
from A
from Base

您可以看到,从 baseMethod 调用的 method() 中的行为发生了变化,输出也发生了变化。但是在 ~A() 析构函数中,行为是相同的。

【问题讨论】:

  • 你指的是“B”(析构函数A中的B),那是什么?另外,不要添加 PS,只是 edit 你的问题来澄清事情。另外,请提供收到的输出和预期的输出,然后解释您期望的原因。这使您的问题更加清晰易懂。

标签: c++


【解决方案1】:

~A() 的主体在 A 的词法范围内。因此,~A() 中的调用 method()静态 绑定到 A::method。不多不少。

因为~A() 被调用,它又调用这个静态绑定的成员函数。

【讨论】:

    猜你喜欢
    • 2013-09-06
    • 2014-11-04
    • 2021-10-20
    • 1970-01-01
    • 2011-09-21
    • 2015-12-30
    • 2016-08-14
    • 2013-02-18
    • 2016-02-29
    相关资源
    最近更新 更多