变量初始化(指针和值) [英] Variable initialization (pointer and value)

查看:233
本文介绍了变量初始化(指针和值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Foo f1 = Foo();      // (1) Ok
Foo f2 = Foo;        // (2) Compiler error

Foo *p1 = new Foo(); // (3) Ok
Foo *p2 = new Foo;   // (4) Ok. Why??

我想知道为什么有两种方法来初始化指针。它看起来有点不一致。是否有一些逻辑原因,如果是,什么?或者,也许是某种遗产?如果是这样,这种符号的起源是什么?

I was wondering why there exists two ways to initialize pointers. It looks a little inconsistent. Is there some logical reason, and if so, what? Or, maybe it's some kind of legacy? And if so, What is the origin of such notation?

推荐答案

这有点...复杂,至少说。

It's a bit... complicated, to say the least.

当处理对象时,两种表示法都是等效的。当处理原始类型(例如 int )时,(3)将初始化(4)不会(该值将保留未定义)。

When dealing with objects, both notations are equivalent. When dealing with primitive types (such as int), (3) will initialize (zero fill) the value, while (4) will not (the value will be left undefined).

对于自动分配的对象, / p>

For automatically allocated objects, this:

Foo f1;

声明并初始化 Foo 默认构造函数。这:

Declares and initializes a Foo object using the default constructor. This:

Foo f2 = Foo();

声明并初始化 Foo 复制构造函数,基本上复制使用默认构造函数构建的临时对象( Foo())的值。

Declares and initializes a Foo object using the copy constructor, essentially copying the value of a temporary object (the Foo()), which is built with the default constructor.

这篇关于变量初始化(指针和值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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