gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:32:32 25 4
gpt4 key购买 nike

这是如何在没有任何警告或错误的情况下编译和运行的?我不明白如何将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com