变量 #
作用:给一段指定内存空间起名字,方便操作这段内存空间
声明语法:数据类型 变量名 = 初始值;
例子:
#include<iostream>
using namespace std;
int main() {
int a = 10;
cout << "声明了一个变量a,初始值是:" << a << endl;
system("pause");
return 0;
}
和java不同的是,cpp中的变量在声明的时候必须赋默认值!!!
常量 #
什么是常量:常量是不可更改的数据
cpp中有两种方法可以声明常量:
#define 常量名 常量值:宏常量- 通常在文件的上方定义,表示一个常量
const 数据类型 常量名 = 常量值:const修饰的变量- 通常在声明变量的前面加const,表示常量
例子:
#include<iostream>
using namespace std;
//切记,宏常量声明后面不需要带分号;
#define day 7
int main() {
const int month = 12;
cout << "一星期有:" << day << "天" << endl;
cout << "一年有:" << month << "月" << endl;
system("pause");
return 0;
}
cpp中的关键字 #
在使用标识符的时候,需要避开这些关键字
| asm | do | if | return | typedef |
|---|---|---|---|---|
| auto | double | inline | short | typeid |
| bool | dynamic_cast | int | signed | typename |
| break | else | long | sizeof | union |
| case | enum | mutable | static | unsigned |
| catch | explicit | namespace | static_cast | using |
| char | export | new | struct | virtual |
| class | extern | operator | switch | void |
| const | false | private | template | volatile |
| const_cast | float | protected | this | wchar_t |
| continue | for | public | throw | while |
| default | friend | register | true | |
| delete | goto | reinterpret_cast | try |
标识符命名规则 #
C++规定给标识符(变量、常量)命名时,有一套自己的规则
- 标识符不能是关键字
- 标识符只能由字母、数字、下划线组成
- 第一个字符必须为字母或下划线
- 标识符中字母区分大小写
建议:给标识符命名时,争取做到见名知意的效果,方便自己和他人的阅读
作用域运算符 #
表明数据、方法的归属性问题
#include <iostream>
using namespace std;
//全局变量
int a = 10;
int main(){
//局部变量
int a = 20;
cout << a << endl; // 优先在局部变量中寻找,找不到再去找全局变量
cout << ::a << endl; // 使用全局变量
return 0;
}