c++ - 为什么不对 initializer_list 中的值进行类型检查?

标签 c++ g++ std initializer-list list-initialization

这是如何在没有任何警告或错误的情况下编译和运行的?我不明白如何将 current 的取消引用值(一个 int)毫无问题地分配给字符串 a

class Test {
public:
  string a;

  Test(initializer_list<int> t) {
    auto current = t.begin();

    // I am assigning an int to a string!
    a = *current;
  }
};

int main() {
  Test test{65};
  printf("%s\n", test.a.c_str());
}

打印出来的字符串是

A

相比之下,这段非常相似的代码会产生编译时错误:

int main() {
  initializer_list<int> test1{65};
  auto current = test1.begin();
  string b = *current;

  return 0;
}

错误是:

error: no viable conversion from 'const int' to 'std::__1::string' (aka 'basic_string<char, char_traits<char>, allocator<char> >')
  string b = *current;

最佳答案

请注意,a = *current;string b = *current; 执行不同的操作。

a = *current; 是一个赋值,它导致调用 operator=,并且 std::string::operator=有一个采用 char 的重载,这使得 a = *current; 工作(在 implicit conversionintchar).

4) Replaces the contents with character ch as if by assign(std::addressof(ch), 1)

string b = *current; 是一个初始化,它试图调用 constructor of std::string初始化b。但是这些构造函数没有这样的重载int(或char),那么string b = *current;将无法工作。

关于c++ - 为什么不对 initializer_list 中的值进行类型检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57239234/

相关文章:

c++ - 无法使用 stat() 区分目录和文件

c++ - 我可以获取标准库中定义的函数的地址吗?

c++ - 未知的缺失库; -lGraf3d、-lPostscript 和 -lPhysics

c++ - 如何仅在C/C++项目中处理宏而不进行编译?

c++ - 为什么 boost::timer 的结果如此奇怪?

c++ - 当给定字符串时,Cout 从行首开始打印

c++ - C++ 标准库中采用右值引用的构造函数

C++ Builder XE,传递和处理用户定义的消息

C++ pragma GCC system_header 指令

c++ - std::equal_to 对于浮点类型是否可靠?