在堆栈上声明一个对象的两种方式之间的区别
以下两个声明之间有什么区别,假设我没有在类 Beatle $ c $中指定复制构造函数和
operator =
c>
What's the difference between the following two declarations, assuming I have not specified a copy constructor and operator=
in class Beatle
?
Beatle john(paul);
和
Beatle john = paul;
编辑:
在对象赋值中,除非另有说明,否则操作符 =
隐式调用复制构造函数? >
In objects assignment, the operator =
implicitly calls the copy constructor unless told otherwise?
它们是不同的语法结构。第一个是直接初始化,第二个是复制初始化。它们的行为几乎相同,只是第二个需要一个非显式的构造函数。
They're different grammatical constructions. The first one is direct initialization, the second is copy initialization. They behave virtually identically, only that the second requires a non-explicit
constructor.*
const int i = 4; code>很好,但
const int i; i = 4;
不是。
To wit: const int i = 4;
is fine, but const int i; i = 4;
is not.
*)更准确地说:如果相关构造函数声明为 explicit
。因此,直接初始化提供了一个自由转换:
*) More accurately: The second version does not work if the relevant constructor is declared explicit
. More generally, thus, direct-initialization affords you one "free" conversion:
struct Foo { Foo(std::string) {} };
Foo x("abc"); // OK: char(&)[4] -> const char * -> std::string -> Foo
Foo y = "abd"; // Error: no one-step implicit conversion of UDTs
要解决您的编辑:要理解赋值运算符,只需将它分成几部分。假设 Foo
有明显的 operator =(const Foo& rhs)
。我们可以说 x = y;
,它直接用 rhs
直接调用操作符 y
。现在考虑这个:
To address your edit: To understand the assignment operator, just break it up into parts. Suppose Foo
has the obvious operator=(const Foo & rhs)
. We can say x = y;
, which just calls the operator directly with rhs
being y
. Now consider this:
x = "abc"; // error, no one-step implicit conversion
x = std::string("abc"); // fine, uses Foo(std::string), then copy
x = Foo("abc"); // fine, implicit char(&)[4] -> const char* -> std::string, then as above