第一章 语法基础
C++语言
是高级语言
支持面向对象的观点和方法
将客观事物看作对象
对象间通过消息传送进行沟通
支持分类和抽象
1 C++ 初识
1.1 第一个 C++ 程序
编写一个 C++ 程序总共分为 4 个步骤:
-
创建项目
-
创建文件
-
编写代码
-
运行程序
第一个 C++ 程序:HelloWorld
#include <iostream>
using namespace std;
int main() {
cout << "HelloWorld" << endl;
//system("pause");
return 0;
}
1.2 注释
注释格式://、/* */
1.3 变量
作用:给一段指定的内存空间起名,方便操作这段内存。
举例:variable.cpp
#include <iostream>
using namespace std;
int main() {
//变量的定义:
//语法:数据类型 变量名 = 初始值
int a = 10;
cout << "a = " << a << endl;
return 0;
}
1.4 常量
作用:用于记录程序中不可更改的数据。
C++ 定义常量两种方式:
-
#define 宏常量:#define 常量名 常量值
-
通常在文件上方定义,表示一个常量
-
-
const 修饰的变量:const 数据类型 常量名 = 常量值
-
通常在变量定义前加关键字 const,修饰该变量为常量,不可修改
-
const 符号常量
-
举例:constant.cpp
#include <iostream>
using namespace std;
//宏常量
#define N 7
int main() {
//N = 5; 不允许修改
cout << N << endl;
//const修饰的变量
const int month = 4;
//month = 5; 不允许修改
cout << month << endl;
return 0;
}
1.5 关键字
作用:关键字是 C++ 中预先保留的单词(标识符)。
| 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 | explict | 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 |
1.6 标识符命名规则
作用:C++ 规定给标识符(变量、常量)命名时,有一套自己的规则。
-
标识符不能是关键字
-
标识符只能由字母、数字、下划线组成
-
第一个字符必须是字母或者下划线
-
标识符中字母区分大小写

最低0.47元/天 解锁文章
26万+

被折叠的 条评论
为什么被折叠?



