new A 与 new A()的区别

Arthas102 2008-11-08 06:01:35

class A
{
...//省略
}

void main()
{
A* p = NULL;
//以下这两种方式有什么区别?请用一个实际的代码例子说明,谢谢!
p = new A;
p = new A();
}
...全文
131 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
Arthas102 2008-11-08
  • 打赏
  • 举报
回复
这标准的英文还真是难以看懂啊
R9R9R9 2008-11-08
  • 打赏
  • 举报
回复
具体的看C++标准的规定吧

ISO/IEC 14882:2003(E) 中 5.3.4 之 15
— 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. If 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);
R9R9R9 2008-11-08
  • 打赏
  • 举报
回复

class foo
{
public:
int val;
};



int main( void )
{


foo* p1 = new foo();
foo* p2 = new foo;

cout << p1->val << endl; // val被初始化为int(),即0
cout << p2->val << endl; // val为随机值

return 0;
}

giant1st 2008-11-08
  • 打赏
  • 举报
回复
A 是一个 Class,权且就当 int 也是个 特殊的Class为例,
p = new A; (1)
p = new A(); (2)
后面的仅仅是多了个初始化,如果有 默认构造函数,(1)就会自己初始化
(2) 是按自己的意愿 来初始化,括号中为初始化的值
new int 的话,会将p所指向的int初始化为0
Arthas102 2008-11-08
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 glacier3d 的回复:]
有区别吗?没有吧
[/Quote]

就是不知道有没有区别才问的阿
zgy1353246 2008-11-08
  • 打赏
  • 举报
回复
看不出区别,等待高手!!!!
glacier3d 2008-11-08
  • 打赏
  • 举报
回复
有区别吗?没有吧

65,187

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧