首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

new A()跟new A 有什么区别

2013-02-15 
new A()和new A 有什么区别?类A;new A()和new A 有什么区别?[解决办法]没有区别都是用默认构造函数[解决办

new A()和new A 有什么区别?
类A;


new A()和new A 有什么区别?
[解决办法]
没有区别

都是用默认构造函数
[解决办法]
A obj;和A obj();
这个是有区别的,后者会被编译器当成一个函数声明(无参,返回类型为A)。
[解决办法]

引用:
类A;


new A()和new A 有什么区别?


我觉得是有区别的。比如,如果在A中你定义了一个带参数的构造函数,那么new A就会出错,而用new A(参数)就OK。

比如:

#include<iostream>
using namespace std;

class A
{
public:
A(int x)
{
}
};
int main()
{
A *a = new A(1);
A *b = new A;// 通过不了编译
return 0;
}


当然如果A中有不带参数的构造函数时,两者的写法效果是一样的。
[解决办法]
没有区别 new A() 等于显式的告诉电脑说 我要申请一块内存存放一个 A类型的数据 并且调用没有参数的构造函数,
[解决办法]
就没有人能勤快点去查查C++标准么,这个区别比较微妙比较小但是比较严重的。
[解决办法]
new A;和new A();可能是不同的!

5.3.4.15
A new-expression that creates an object of type T initializes that object as follows:
If the new-initializer is omitted:
if T is a (possibly cv-qualified) non-POD class type (or array thereof), the object is default-
initialized (8.5). If T is a const-qualified type, the underlying class type shall have a user-declared
default constructor.
— Otherwise, the object created has indeterminate value. I T is a const-qualified type, or a (possibly
cv-qualified) POD class type (or array thereof) containing (directly or indirectly) a member of
const-qualified type, the program is ill-formed;
— If the new-initializer is of the form (), the item is value-initialized (8.5);


8.5.5
To value-initialize an object of type T means:
if T is a class type (clause 9) with a user-declared constructor (12.1), then the default constructor for T is
called (and the initialization is ill-formed if T has no accessible default constructor);
if T is a non-union class type without a user-declared constructor, then every non-static data member
and base-class component of T is value-initialized;

热点排行