为什么 c++ 编译器不会针对以下代码报错?
#include<iostream>
int main()
{
const char* p ="Hello";
std::string q = p + 'H';
std::cout << q << std::endl;
}
它正确地为以下代码抛出错误
#include<iostream>
int main()
{
const char* p ="Hello";
std::string q = p + "World";
std::cout << q << std::endl;
}
编译器抛出的错误语句
test.cxx: In function 'int main()':
test.cxx:5: error: invalid operands of types 'const char*' and 'const char [6]' to binary 'operator+'
有人可以帮助我理解为什么第一个代码没有抛出任何错误语句吗?
最佳答案
'H'
是一个字符,一个整型。所以 p + 'H'
与 &p['H']
相同(您是根据 'H'
的数值进行索引).第一个代码片段具有未定义的行为,因为 'H'
的数值可能远大于 6,但编译器可以自由选择不提示未定义的行为。
另一方面,"World"
不是整数类型,也不能转换为 one。所以不能进行加法,点空白。
关于c++ - 为什么编译器不提示将 char 添加到 char*?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47030649/