在C ++中构造对象的不同方法 [英] Different ways of constructing an object in C++

查看:166
本文介绍了在C ++中构造对象的不同方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在栈中构造一个对象,使用C ++。
你知道这些方法与调用构造函数(带和不带括号)的区别是什么:

I want to construct an object in the stack, using C++. Do you know what is the difference between these to ways of calling the constructor (with and without parenthesis):

a)
MyClass object;

b)
MyClass object();

我使用MFC和构建主应用程序的全局变量,如果我使用后一种方式,我得到一个异常,我认为这两种方式

I am using MFC and when constructing the global variable for the main app, if I use the latter way, I get an exception, I thought these two ways were equivalent.

感谢您提供任何资讯。

推荐答案

是C ++的那些陷阱之一。

This is one of those gotchas of C++.

MyClass object();

是在C ++中定义函数原型的方式,因此编译器认为你正试图在另一个函数的中间声明另一个函数。

is the way that a function prototype is defined in C++, so the compiler thinks you are trying to declare another function in the middle of another function.

如果你想调用默认的构造函数(即没有参数)这个语法改为:

If you want to invoke the default constructor (i.e. the one which takes no arguments), use this syntax instead:

MyClass object;

这篇关于在C ++中构造对象的不同方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆