使用()或不使用创建对象的区别 [英] Difference between creating object with () or without
问题描述
我刚刚遇到问题
错误:请求成员'show'在'myWindow'当尝试编译一个简单的qt应用程序时,类型类型'MainGUIWindow()'
< >
#include< QApplication>
#includegui / MainGUIWindow.h
int main(int argc,char ** argv)
{
QApplication app argv);
MainGUIWindow myWindow();
myWindow.show();
return app.exec();
}
我解决了这个问题,替换
MainGUIWindow myWindow();
由
MainGUIWindow myWindow;
但我不明白差别。
其他答案正确地说明括号版本实际上是一个函数声明。为了直观地理解它,假设你写了 MainGUIWindow f();
看起来更像一个函数,不是吗?
更有趣的问题是
MainGIUWindow * p = new MainGIUWindow;
和
MainGIUWindow * p = new MainGIUWindow();
带括号的版本称为值初始化,而不带版本的版本称为默认初始化。对于非POD类,两者之间没有区别。对于POD结构,值初始化包括将所有成员设置为0,
my2c
一般来说,如果一些句法结构可以解释为声明和别的东西,编译器 总是解决有利于声明 的歧义。
i just run into the problem
error: request for member ‘show’ in ‘myWindow’, which is of non-class type ‘MainGUIWindow()’
when trying to compile a simple qt-application:
#include <QApplication>
#include "gui/MainGUIWindow.h"
int main( int argc, char** argv )
{
QApplication app( argc, argv );
MainGUIWindow myWindow();
myWindow.show();
return app.exec();
}
I solved this by replacing
MainGUIWindow myWindow();
by
MainGUIWindow myWindow;
but I don't understand the difference. My question: What is the difference?
Regards, Dirk
The other answers correctly state that the parentheses version is actually a function declaration. To understand it intuitively, suppose you wrote MainGUIWindow f();
Looks more like a function, doesn't it? :)
The more interesting question is what is the difference between
MainGIUWindow* p = new MainGIUWindow;
and
MainGIUWindow* p = new MainGIUWindow();
The version with parentheses is called value-initialization, whereas the version without is called default-initialization. For non-POD classes there is no differnce between the two. For POD-structs, however, value-initialization involes setting all members to 0,
my2c
Addition: In general, if some syntactic construct can be interpreted both as a declaration and something else, the compiler always resolves the ambiguity in favor of the declaration.
这篇关于使用()或不使用创建对象的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!