簡體   English   中英

Qt控制台方案中未調用析構函數

[英]Destructor not called in Qt console scenario

我有一個看似太簡單的問題,但無論如何我想理解答案。

示例代碼如下。


   #include <QtCore/QCoreApplication>
    #include "parent.h"
    #include "childa.h"
    #include "childb.h"

    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);

        Parent one;
        ChildA two;
        ChildB three;

        return a.exec();
    }

#ifndef CHILDA_H
#define CHILDA_H

#include <iostream>
#include "parent.h"

using namespace std;

class ChildA : public Parent
{
public:
    ChildA();
    ~ChildA();
};

#endif // CHILDA_H

  #ifndef CHILDB_H
    #define CHILDB_H

    #include <iostream>
    #include "parent.h"

    using namespace std;

    class ChildB : public Parent
    {
    public:
        ChildB();
        ~ChildB();
    };

    #endif // CHILDB_H

#ifndef PARENT_H
#define PARENT_H

#include <iostream>

using namespace std;

class Parent
{
public:
    Parent();
    virtual ~Parent();
};

#endif // PARENT_H

#include "childa.h"

ChildA::ChildA()
{
    cout << "in Child A const\n";
}

ChildA::~ChildA()
{
    cout << "in Child A destructor\n";
}

#include "childb.h"

ChildB::ChildB()
{
    cout << "in Child B const\n";
}

ChildB::~ChildB()
{
    cout << "in Child B destructor\n";
}

#include "parent.h"

Parent::Parent()
{
    cout << "in Parent const\n";
}

Parent::~Parent()
{
    cout << "in Parent destructor\n";
}

為什么我看不到析構函數被調用?
對象變量應該超出main范圍,應該調用析構函數,不是嗎?

您的對象永遠不會超出范圍,因為您的應用程序不存在(即您不會超出main函數的范圍)。 您需要關閉您的應用程序,並且您需要這樣做:

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    Parent one;
    ChildA two;
    ChildB three;
    // This will immediately terminate the application
    QTimer::singleShot(0, &a, SLOT(quit()));
    return a.exec();
}

請注意,您可以將計時器設置為在特定的時間執行,例如,在上面的示例中,我將其設置為在0毫秒后執行。

如果您不想關閉應用程序,則可以強制作用域

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    // Force scope
    {
        Parent one;
        ChildA two;
        ChildB three;
    }

    return a.exec();
}

暫無
暫無

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

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