簡體   English   中英

在 C++ 中調用了兩次析構函數

[英]Destructor called two times in C++

我有兩個這樣的類的代碼:

Class A:

class A {
    int a, b;
public:
    A(int x, int y) {
        a = x;
        b = y;
    }
    ~A() {
        cout << "Exit from A\n";
    }
    void values() {
        cout << a << "\n" << b << endl;
    }
};

Class B:

class B :public A
{
    int c;
public:
    B(int x, int y, int z) :A(x, y)
    {
        c = z;
    }
    ~B() {
        cout << "Exit from B\n";
    }
    void values() {
        A::values();
        cout << c << endl;
    }
};

和主要的function:

int main()
{
    A testA(1, 2);
    testA.values();
    B testB(10, 20, 30);
    testB.values();
}

這就是我得到的:

1
2
10
20
30
Exit from B
Exit from A
Exit from A

首先從 class B 調用析構函數,然后從 A 調用兩次。 為什么要兩次? 我不知道如何改變它。

maintestAtestBA基子對象中創建了 2 個A對象。 兩者都在 main 結束時被銷毀,與它們的聲明順序相反。

class A {
    int a, b;
    std::string msg;
protected:
    A(int x, int y, std::string m) : a(x), b(y), msg(m) {}
public:
    A(int x, int y) : A(x, y, "Exit from A\n") {}
    virtual ~A() {
        std::cout << msg;
    }
    virtual void values() {
        std::cout << a << "\n" << b << std::endl;
    }
};

class B :public A
{
    int c;
public:
    B(int x, int y, int z) : A(x, y, "Exit from B\n"), c(z) {}
    void values() override {
        A::values();
        std::cout << c << std::endl;
    }
};

你有 Object testA它將從A (1) 調用它的析構函數。 您有 Object testB ,它是從A派生的,因此它將調用析構函數B (1) 和析構函數A (2)。

這正是您的 output 所說的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM