【发布时间】:2020-04-11 19:29:18
【问题描述】:
在 c++ 中,我可以通过多种方式创建和初始化变量:
int x = 0;
int x(0);
int x = int(0);
int x = int(); // same as zero
但例如在声明此类非原始数据类型时,会出现某种错误。
string s = "";
string s("");
string s = string("");
string s = string(); // gives an error
这些类型的初始化有什么区别,为什么最后一种类型适用于int而不适用于string?
【问题讨论】:
-
string s = string();代码行出现什么错误? -
最后一行是多余的。字符串 s;将调用默认构造函数。这样做将调用 operator= 并调用默认构造函数
-
我在该代码中看到的唯一错误是
s被重用,我想你知道这一点。不过,请确保您删除了同一范围内的其他ss。
标签: c++ variables constructor initialization declaration