1 C++初识
1.1 第一个C++程序
编写一个C++程序总共分为4个步骤
- 创建项目
- 创建文件
- 编写代码
- 运行程序
1.1.1创建项目
Visual Studio是常用工具用来编写C++
创建空项目
1.1.2创建文件
右击源文件——添加——新建项——给文件起名称——确定
1.1.3编写代码
#include <iostream>
using namespace std;
int main()
{
cout << "hello world" << endl;
system("pause");
return 0;
}
1.1.4 运行程序
hello world
请按任意键继续. . .
1.2 注释
两种格式
1. 单行注释: //描述信息
- 通常放在一行代码的上方,或者一条语句的末尾,该代码进行说明
2.多行注释: /*描述信息*/
- 通常在一段代码的上方,对该段代码做整体说明
1.3变量
变量存在的意义:方便我们管理内存空间
创建变量的语法: 数据类型 变量名 = 变量初始值;
#include <iostream>
using namespace std;
int main()
{
//变量的创建
int a = 5;
cout << "a=" << a << endl;
system("pause");
return 0;
}
运行结果 a=5
1.4 常量
作用:用于记录程序中不可更改的数据
C++定义常量两种方式
1. #define 宏常量:#define 常量名 常量值
通常在文件上方定义:表示为一个常量
2. const修饰的变量:const 数据类型 常量名 = 常量值
通常在变量定义前加关键字const,修饰该变量为常量,不可更改
示例:
#include <iostream>
using namespace std;
//常量的定义方式
//1. #define 宏常量
//2. const修饰的变量
//1. #define 宏常量
#define Day 7
int main()
{
cout << "一周总共有" << Day << "天"<<endl;
//Day = 8;//修改会报错
//2.const修饰的变量
const int month = 12;
//month = 24; //报错,不可修改
cout << "一年总共有" << month << "个月份" << endl;
system("pause");
return 0;
}
1.5 关键字
作用:关键字是C++中预先保留的单词(标识符)
- 在定义变量或者常量时候,不要用关键字
C++关键字如下:
asm | do | if | return | typedef |
auto | double | inline | short | typeid |
bool | dynamic_cast | int | signed | typename |
break | else | long | sizedf | union |
case | enum | mutable | static | unsigned |
catch | explicit | namespace | static_cast | using |
char | export | new | struct | virtual |
class | extern | operator | switch | void |
const | faise | 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++规定给标识符(变量、常量)命名时,有一套自己的规则
- 标识符不能时关键字
- 标识符只能由字母、数字、下划线组成
- 第一个字符必须为字母或下划线
- 标识符中字母区分大小写