如果 char 和 int 只是位数不同,为什么它们在打印时不同?
If char and int differ only in the number of bits, why are they different when printing?
在 中,接受的答案表示不同之处在于位的大小。虽然,MicroVirus 回答说:
it plays the role of a character in a string, certainly historically. When seen like this, the value of a char maps to a specified character, for instance via the ASCII encoding, but it can also be used with multi-byte encodings (one or more chars together map to one character).
基于这些答案:在下面的代码中,为什么输出不一样(因为它只是位数不同)?是什么机制让每种类型打印出不同的“字符”?
#include <iostream>
int main() {
int a = 65;
char b = 65;
std::cout << a << std::endl;
std::cout << b << std::endl;
//output :
//65
//A
}
A char
可能被视为包含数值,当 char
被这样对待时,它确实与 int
的大小不同——它更小,通常一个字节。
但是,int
和 char
仍然是 不同的类型 ,并且由于 C++ 是一种静态类型的语言,因此类型很重要。变量的类型会影响程序的行为,而不仅仅是变量的值。在您的问题中,两个变量的打印方式不同,因为运算符 <<
超载了;它以不同的方式对待 int
和 char
。
在
it plays the role of a character in a string, certainly historically. When seen like this, the value of a char maps to a specified character, for instance via the ASCII encoding, but it can also be used with multi-byte encodings (one or more chars together map to one character).
基于这些答案:在下面的代码中,为什么输出不一样(因为它只是位数不同)?是什么机制让每种类型打印出不同的“字符”?
#include <iostream>
int main() {
int a = 65;
char b = 65;
std::cout << a << std::endl;
std::cout << b << std::endl;
//output :
//65
//A
}
A char
可能被视为包含数值,当 char
被这样对待时,它确实与 int
的大小不同——它更小,通常一个字节。
但是,int
和 char
仍然是 不同的类型 ,并且由于 C++ 是一种静态类型的语言,因此类型很重要。变量的类型会影响程序的行为,而不仅仅是变量的值。在您的问题中,两个变量的打印方式不同,因为运算符 <<
超载了;它以不同的方式对待 int
和 char
。