问题
Let's say, we have:
char x = 'a';
int y = 1;
So, if you run:
std::cout << x + y;
It prints 98 instead of 'b'. As i see from here
<<operator
has only int parameter implementation.
From now on i have 2 questions:
- After char + int operation what type is returned?
- Why there is no char parameter implementation, but
std::cout << x
still works as expected and prints char value?
回答1:
Thanks to Fefux, Bo Persson and Matti Virkkunen answers are:
From CPP Reference: Implicit conversions:
arithmetic operators do not accept types smaller than
int
as arguments, and integral promotions are automatically applied after lvalue-to-rvalue conversion, if applicable.So return type of
x + y
isint
.std::cout
has aoperator<<(char)
as a non-member.
回答2:
As you probably know, C++ is backward compatible with C.
Both C & C++ treat char
s like int
s.
You may consider this a flaw of the language, but on the contrary, this is very handy.
Suppose you want to convert a capital letter to the corresponding small letter. Since any capital letter has an ASCII code 32 below the corresponding small letter, this is as simple as this:
char c = 'A';
std::cout << (char) (c + 32); // output: 'a'
Inversely you can convert from small letter to capital letter:
char c = 'a';
std::cout << (char) (c - 32); // output: 'A'
来源:https://stackoverflow.com/questions/40785687/c-why-stdcout-char-int-prints-int-value