簡體   English   中英

C++如何使用派生類構造函數銷毀基類中的對象

[英]C++ how to destroy an object in the base class with a derived class constructor

因此,在我的程序中,我有一個名為 hangman 的派生類和一個名為 HangmanGraphics 的派生類。 我遇到的問題是在游戲結束后我想重置我的變量,但由於某種原因,我的基本構造函數沒有重新啟動甚至沒有被調用。 當我運行程序時,它將轉到基本構造函數一次,但在程序結束時:

#include "player.h"
#include "hangman.h"
#include "HangmanGraphics.h"

using namespace std;

int main()
{

    HangmanGraphics game2;
    while(1)
    {
        game2.Play();

        if(game2.Play()=='Y')
        {
            game2=HangmanGraphics();

            //in this part of the code I want to reset my base
            //constructor values but how do I do that by using the 
            //derived construtor  

            continue;
        }
    }
}

便宜的黑客。 將 game2 的定義移動到 while 循環中將在每次通過循環時提供一個新的 game2:

int main()
{
    while(1)
    {
        HangmanGraphics game2; // game2 created here
        // do stuff
    } // game2 destroyed here
}

您的問題中沒有提供足夠的信息來說明這是一件好事還是一件壞事。 但...

game2=HangmanGraphics();

會做五件事:

  1. 調用 HangmanGraphics 的構造函數來創建一個臨時的 HangmanGraphics。
  2. 這導致調用 Hangman 的構造函數
  3. 調用 HangmanGraphics 的 = 運算符。 如果未指定,則默認將右側 HangmanGraphics 的內容復制到左側。 它將復制一個指針,但不會復制指向的數據。
  4. 在臨時 HangmanGraphics 上調用析構函數
  5. 這導致調用 Hangman 的析構函數

如果您在 HangmanGraphics 或 Hangman 中有任何動態分配的存儲空間,則需要閱讀三法則

在臨時 HangmanGraphics 及其基礎 Hangman 中動態分配的任何內容都將(或應該)被析構函數刪除。 如果 operator= 不是自定義定義來處理動態數據,那么 game2 現在包含指向無效存儲的指針。

例子:

class base
{
public:
    base(): baseval(number++), interestingData(new int(number++))
    {
        cout << "base ctor " << baseval << "," << * interestingData <<endl;
    }
    virtual ~base()
    {
        cout << "base dtor " << baseval << "," << * interestingData <<endl;
        delete interestingData;
    }
private:
    int baseval;
    int * interestingData;
};

class derived: public base
{
public:
    derived():base()
    {
        cout << "derived ctor" <<endl;
    }
    virtual ~derived()
    {
        cout << "derived dtor" <<endl;
    }
    derived & operator=(const derived & rhs) //only exists to do the cout
    {
        cout << "derived =" <<endl;
        base::operator=(rhs);
        return *this;
    }
};

int main()
{
    derived test;
    cout << "created test" << endl;
    test = derived();
    cout << "exit" << endl;
}

輸出

base ctor 0,1
derived ctor
created test
base ctor 2,3
derived ctor
derived =
derived dtor
base dtor 2,3
exit
derived dtor
base dtor 2,4067440

最后一次打印中的有趣數據被粉碎,因為它指向的地址已被重新分配。 更有趣的是,它即將被第二次刪除,這將使您的程序崩潰。

暫無
暫無

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

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