C++学习笔记-Variable

C++是强类型语言,定义变量时需要明确变量的数据类型,如下所示:

1
2
int iNumber = 8; // 4byte
std::cout << iNumber << std::endl;

在C++中,无符号数用关键字 unsigned 定义

1
2
3
4
// 在计算机中,计算机存储的数据是不分什么正数负数的,它就是存储一个数据在哪,至于是正数还是负数,是看使用它的人怎么看待它。
// 那么我们一般如果不需要负数的表示形式的话,我就可以把它看成是无符号数
unsigned int uNumber = 8; // 无符号整数
std::cout << uNumber << std::endl;

sizeof 关键字可以检查一个类型占多少个字节

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>

int main() {
	// 注意这里为了打印结果时更清晰,使用了std::to_string,它是C++11引入了的函数,它可以将整数转换为字符串。
	// 因为sizeof的结果不能直接和字符串拼接,需要转换成字符串。
	std::cout << "sizeof(int) = " + std::to_string(sizeof(int)) << std::endl;
	std::cout << "sizeof(char) = " + std::to_string(sizeof(char)) << std::endl;
	std::cout << "sizeof(short) = " + std::to_string(sizeof(short)) << std::endl;
	std::cout << "sizeof(long) = " + std::to_string(sizeof(long)) << std::endl;
	std::cout << "sizeof(long long) = " + std::to_string(sizeof(long long)) << std::endl;
	std::cout << "sizeof(float) = " + std::to_string(sizeof(float)) << std::endl;
	std::cout << "sizeof(double) = " + std::to_string(sizeof(double)) << std::endl;
	std::cout << "sizeof(bool) = " + std::to_string(sizeof(bool)) << std::endl;

	// 数据类型的不同只是数据的表示形式不一样,不代表它只能存储某种类型的数据
	char c2 = 'A';
	char c3 = 65;
	std::cout << c2 << std::endl; // A
	std::cout << c3 << std::endl; // 也会输出字符 'A',尽管 c3 是以整数值 65 存储的,但 std::cout 在输出 char 类型的变量时会将其解释为字符,并输出对应的 ASCII 码值的字符。
}
updatedupdated2025-03-032025-03-03