0.简介
面向对象编程(OOP)的本质是设计并扩展自己的数据类型。设计自己的数据类型就是让类型与数据匹配。
1.简单变量
程序通常都需要存储信息——如成都今天天气的湿度、美国疫情感染人数等等;
计算机存储信息,程序必须记住3种不同的属性:
- 信息将存储在哪里;
- 要存储什么值;
- 存储何种类型的信息;
常用策略是声明变量。事实上,声明变量是指,程序将找到一块能够存储该数据类型的的内存,将该内存单元标记为变量名,并将存储的值复制到该内存单元内中;然后,就可以在程序中使用变量名来访问该内存单元。
1.1 变量名
- 在名称中只能使用字母字符、数字和下划线;
- 名称的第一个字符不能是数字;
- 区分字符大小写;
- 不能用关键字作名称;
- 以两个下划线或下划线和大写字符打头的名称将被保留给实现使用。输出不确定。
1.2 整形
整数就是没有小数部分的数字,如2、56、999。整数可以是无限的,计算资源却不可以。因此,计算机往往只能表示其中的一些子集,整形的前身。
c++基本整形:char(常用来表示字符,而非数字), short, int, long, long long,其中每种类型都有符号版本和无符号版本。
计算机内存由一些叫做位(bit)的单位组成。字节(byte)通常指的是8位的内存单元。由此来看,字节指的是计算机内存量的度量单位, 1KB=1024字节,1MB=1024KB.
- short至少16位;
- int至少与short一样长;
- long至少32位,且至少与int一样长;
- long long至少64位,且至少与long一样长。
符号类型例程:
# include <iostream>
# include <climits>
int
main()
{
using namespace std;
int n_int = INT_MAX; //初始化将赋值与声明结合在一起
short n_short = SHRT_MAX;
long n_long = LONG_MAX;
long long n_llong = LLONG_MAX;
// sizeof
运算符
返回类型或变量的长度
cout << "int is " << sizeof(int) << "bytes." << endl;
cout << "short is " << sizeof(short) << "bytes." << endl;
cout << "long is " << sizeof(long) << "bytes." << endl;
cout << "long long is " << sizeof(long
long) << "bytes." << endl;
cout << endl;
cout << "Maximum values: " << endl;
cout << "int: " << n_int << endl;
cout << "short: " << n_short << endl;
cout << "long: " << n_long << endl;
cout << "long long: " << n_llong << endl << endl;
cout << "Minimum values: " << endl;
cout << "Bits per byte = " << CHAR_BIT << endl;
return 0;
}
结果显示:
Maximum values:
int: 2147483647
short: 32767
long: 2147483647
long long: 9223372036854775807
Minimum values:
Bits per byte = 8
请按任意键继续. . .
无符号类型例程:
# include <iostream>
# define ZERO 0
# include <climits>
int
main()
{
using namespace std;
short sam = SHRT_MAX;
unsigned short sue = sam;
cout << "Sam has " << sam << " dollars and Sue has " << sue;
cout << " dollars deposited." << endl \
<< "Add $1 to each account." << endl << "Now ";
sam = sam + 1;
sue = sue + 1;
cout << "Sam has " << sam << " dollars and Sue has " << sue;
cout << " dollars deposited.\nPoor Sam!" << endl;
sam = ZERO;
sue = ZERO;
cout << "Sam has " << sam << " dollars and Sue has " << sue;
cout << "Take $1 from each account." << endl << "Now ";
sam = sam - 1;
sue = sue - 1;
cout << "Sam has " << sam << " dollars and Sue has " << sue;
cout << " dollars deposited." << endl << "Lucky Sue!" << endl;
return 0;
}
结果显示:
Sam has 32767 dollars and Sue has 32767 dollars deposited.
Add $1 to each account.
Now Sam has -32768 dollars and Sue has 32768 dollars deposited.
Poor Sam!
Sam has 0 dollars and Sue has 0
Take $1 from each account.
Now Sam has -1 dollars and Sue has 65535 dollars deposited.
Lucky Sue!
请按任意键继续. . .
整型变量的行为就像是里程表。如果超越了限制,其值将为范围另一端的取值。C++确保无符号类型的这种行为,但不确保符号整型超越限制(上溢和下溢)不出错。