#include <iostream>
int main()
{
const std::string exclam = "!";
const std::string message = "Hello" + ", world" + exclam;
std::cout << message;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么这段代码不起作用?错误返回:
error: invalid operands of types `const char[6]' and `const char[8]' to binary `operator+'
Run Code Online (Sandbox Code Playgroud)
提前致谢!
编辑:
感谢所有的答案.这是我第一次访问该网站,我对如此短暂的时间间隔内精心解释的数量感到惊讶.
关于实际问题.那为什么会这样:
const std::string hello = "Hello";
const std::string message = hello + ", world" + "!";
Run Code Online (Sandbox Code Playgroud)
是因为",世界"还是之后"!" 得到与变量hello(定义)连接?
jal*_*alf 21
因为在C++中,字符串文字(类似于"Hello"不是类型std::string.它们是普通字符数组或C风格字符串.
因此,对于该行const std::string message = "Hello" + ", world" + exclam;,编译器必须使用的类型是:
const std::string message = const char[6] + const char[8] + std::string;
并且考虑到+它的相关性,它必须执行的操作是:
const std::string message = ((const char[6] + const char[8]) + std::string);
也就是说,必须首先评估最左边的添加,并将结果传递给最右边的添加.
所以编译器试图评估const char[6] + const char[8].没有为数组定义添加.数组被隐式转换为指针,但这对编译器没有帮助.这只意味着它最终结束const char* + const char*,并且没有为指针定义添加.
此时,它不知道您希望将结果转换为a std::string.
但是,在你的第二个例子中:
const std::string hello = "Hello";
const std::string message = hello + ", world" + "!";
Run Code Online (Sandbox Code Playgroud)
它有效,因为编译器会看到的操作std::string + const char[8] + const char[2].这里,第一加法可以被转换成std::string + const char*,这里的加法运算符被定义,并返回一个std::string.所以编译器已成功找到第一个加法,并且由于结果是一个字符串,第二个加法看起来像这样:std::string + const char[2]和以前一样,这是不可能的,但是数组可以转换为指针,然后编译器能够找到一个有效的加法运算符,再次产生一个std::string.
Dou*_* T. 16
"Hello" + ", world"
Run Code Online (Sandbox Code Playgroud)
由于这些是c风格的字符串,因此无法用+附加它们.你可以将一个std :: string附加到一个c风格的字符串,但不能用这种方式附加2个c风格的字符串,而是在其中一个字符串周围添加一个std :: string()构造函数来创建一个临时字符串,即:
"Hello" + std::string(", world")
Run Code Online (Sandbox Code Playgroud)
C++没有做其他OO语言的许多自动"幕后"对话.
正如Doug所说,你需要做std :: string("hello")+ std :: string("world"),这种语言不适合你.
但是你可以做到
std::cout << "hello" << "world" << exclam;
Run Code Online (Sandbox Code Playgroud)
因为std :: cout知道如何打印const char []以及字符串
字符串文字只是 C++ 中以零结尾的字符数组。C++ 中没有允许您添加 2 个字符数组的运算符。
然而,有一个 char 数组和 std::string + 运算符。
改成:
const std::string message = std::string("Hello") +", world" + exclam;
Run Code Online (Sandbox Code Playgroud)
在某些语言(如 Python)中,字符串文字相当于字符串类型的变量。C++ 不是这样的语言。
| 归档时间: |
|
| 查看次数: |
7290 次 |
| 最近记录: |