繁体   English   中英

为什么initializer_list中的值没有经过类型检查?

[英]Why aren't values in initializer_list type-checked?

如何在没有任何警告或错误的情况下编译和运行? 我不明白如何将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; work(在从intchar隐式转换之后)。

4)用字符ch替换内容,就像assign(std::addressof(ch), 1)

string b = *current; 是一个初始化,它试图调用std::string构造函数来初始化b 但是这些构造函数没有这样的重载采用int (或char ),然后string b = *current; 不行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM