C++ 字符串 cout 字符丢失

C++ string cout character lost

这是 Visual studio 中的控制台应用程序,所以我想看看如果我在 cout 中调用 cout 会发生什么。它有点工作,但它删除了一个有点奇怪的角色。因此它从 main 中的 cout 中删除了 string 中的字符数量。因此它删除了与 doPrint() 函数的 return 值一样多的字符。

示例: 如果 return 值为 1,它将输出 "AAAAABLLLLLLLLLL" 如果 return 值为 2,它将输出 "AAAAALLLLLLLLLL"

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

int doPrint()
{
    std::cout << "AAAAA" << std::endl;
    return 1;
}

int main()
{
    std::cout << "BBLLLLLLLLLL" + doPrint() << std::endl;
    int x;
    std::cin >> x;
    return 0;
}

这没什么大不了的,但我想知道为什么会这样。 已经谢谢了。

P.S:我知道我应该做 << 而不是 +

嗯,基本上发生的是指针运算和指定的函数调用求值顺序。

"BBLLLLLLLLLL" + doPrint()

所以

"BBLLLLLLLLLL" + 1 

产量

BLLLLLLLLLL

"BBLLLLLLLLLL" + 2 

产量

LLLLLLLLLL

std::cout.

它对字符数组字面量和 "looses" 个字符应用函数指针算法,因为 doPrint() 产生的结果比 0 大。

+的运算符优先级高于<<,因此doPrint()先被调用并打印AAAAA。所以你的状态

 std::cout << "BBLLLLLLLLLL" + doPrint() << std::endl;

分解为

  1. 致电doPrint()
    1.1.打电话 std::cout << "AAAAA" << std::endl;
  2. doPrint()
  3. 的结果值调用"BBLLLLLLLLLL" + 1
  4. 致电std::ostream& operator<<(std::otream&, const char*)
  5. 致电std::endl