2016-11-24 150 views
3

比方說,我們有:C++。爲什麼std :: cout << char + int打印int值?

char x = 'a'; 
int y = 1; 

所以,如果你運行:

std::cout << x + y; 

它打印出98,而不是 'B'。正如我從here看到的 <<operator只有int參數實現。

從現在開始,我有2個問題:

  1. 字符+ INT操作後返回什麼類型?
  2. 爲什麼沒有char參數實現,但std::cout << x仍然按預期工作並打印char值?
+4

閱讀:HTTP ://en.cppreference.com/w/cpp/language/implicit_conversion(Section Numeric promotions - > Integral promotion) – Fefux

+1

2)還有一套[非會員運營商<<](http://www.cplusplus。com/reference/ostream/ostream/operator-free /),它也適用於流。 –

+2

而這個:http://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt2用於爲'char'實現'operator <<'。你應該忘記cplusplus.com,這不是一個非常全面的網站。 –

回答

-3

正如你可能知道,C++向後與C.

兼容這兩種Ç& C++對待char就像int秒。

您可能認爲這是該語言的缺陷,但恰恰相反,這非常方便。

假設您要將大寫字母轉換爲相應的小寫字母。由於任何大寫字母低於相應的小寫字母的ASCII碼32,這是如此簡單:

char c = 'A'; 

std::cout << (char) (c + 32); // output: 'a' 

反之則可以從小寫字母轉換爲大寫字母:

char c = 'a'; 

std::cout << (char) (c - 32); // output: 'A' 
+8

「*您可能知道,C++向後兼容C. *」可悲的是,這不是事實。 –

+0

@GillBates,幾乎如此。而「幾乎」就足夠了。 – user7140484

+4

在你的答案的任何地方都找不到「幾乎」。 –

相關問題