+运算符在cout中做了什么?

Cel*_*tas 4 c++ iostream

在下面的代码中,我感到困惑并添加了一个+应该是<<的地方

#include <iostream>
#include "Ship.h"

using namespace std;

int main()
{
    cout << "Hello world!" << endl;
    char someLetter = aLetter(true);
    cout <<"Still good"<<endl;
    cout << "someLetter: " + someLetter << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

应该

cout << "someLetter: " << someLetter << endl;
Run Code Online (Sandbox Code Playgroud)

输出的代码不正确:

你好,世界!
还是很好的
os :: clear

我不明白为什么编译器没有捕获任何错误,os :: clear意味着什么?为什么在行的开头不是"someLetter:"?

Fré*_*idi 8

这里"someLetter: "是一个字符串文字,即一个const char *指针,通常指向存储所有字符串文字的只读存储区域.

someLetter是a char,因此"someLetter: " + someLetter执行指针运算并将值添加someLetter到存储在指针中的地址.最终结果是指针指向您要打印的字符串文字的某个位置.

在您的情况下,似乎指针最终在符号表中并指向ios::clear方法名称的第二个字符.这完全是任意的,指针可能最终指向另一个(可能无法访问)位置,具体取决于someLetter字符串文字存储区域的值和内容.总之,这种行为是未定义的,你不能依赖它.