变量初始化(指针和值)

变量初始化(指针和值)

问题描述:

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.