【问题标题】:What is the difference between these types of initialization?这些类型的初始化有什么区别?
【发布时间】: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?

【问题讨论】:

标签: c++ variables constructor initialization declaration


【解决方案1】:

它们在功能上是等效的。 这是带有详细信息的漂亮页面https://en.cppreference.com/w/cpp/language/initialization

int x(0); // direct initialization

// These three are copy initialization with copy elision
int x = 0;
int x = int(0);
int x = int();

/// not initialization!!! declaration of function
int x();

对于字符串的情况类似,虽然你也可以根据你在初始化时给出的参数来选择不同的构造函数。

【讨论】:

  • 我可以像这样初始化 string s = string(); 并且没有错误,但是当我在它之后写 cout << s << endl; 时,错误看起来像这样 - error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)
  • @K2osha 尝试在程序顶部添加#include <string>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-07
  • 2011-02-26
  • 2011-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多