C++ 在Qt控制台场景中未调用析构函数
我有一个问题可能看起来太简单了,但我想知道答案 示例代码如下C++ 在Qt控制台场景中未调用析构函数,c++,qt,C++,Qt,我有一个问题可能看起来太简单了,但我想知道答案 示例代码如下 #包括 #包括“parent.h” #包括“childa.h” #包括“儿童B.h” int main(int argc,char*argv[]) { qcorea应用程序(argc、argv); 亲本; ChildA 2; 三个孩子; 返回a.exec(); } \ifndef CHILDA\u H #给孩子下定义 #包括 #包括“parent.h” 使用名称空间std; ChildA类:公共家长 { 公众: ChildA()
#包括
#包括“parent.h”
#包括“childa.h”
#包括“儿童B.h”
int main(int argc,char*argv[])
{
qcorea应用程序(argc、argv);
亲本;
ChildA 2;
三个孩子;
返回a.exec();
}
\ifndef CHILDA\u H
#给孩子下定义
#包括
#包括“parent.h”
使用名称空间std;
ChildA类:公共家长
{
公众:
ChildA();
~ChildA();
};
#endif//CHILDA_H
\ifndef CHILDB\H
#给孩子下定义
#包括
#包括“parent.h”
使用名称空间std;
B类:公共家长
{
公众:
ChildB();
~ChildB();
};
#endif//CHILDB_H
\ifndef PARENT\u H
#定义父项
#包括
使用名称空间std;
班级家长
{
公众:
父项();
虚拟~Parent();
};
#endif//PARENT_H
#包括“childa.h”
ChildA::ChildA()
{
cout您的对象永远不会超出范围,因为您的应用程序不存在(即,您没有超出主功能的范围)。您需要关闭应用程序,然后按如下方式操作:
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();
}
因此,基本上,Qt控制台应用程序不会在main耗尽要运行的指令时结束?@user440297 main从不“耗尽指令”。执行在.exec()中暂停,等待事件发生。因为您没有生成任何事件(如请求应用程序退出),所以它位于QApplication::exec()中事件循环永远在等待某事发生。
#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";
}
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();
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// Force scope
{
Parent one;
ChildA two;
ChildB three;
}
return a.exec();
}