1.1 第一个C++程序
编写一个C++程序总共分为4个步骤
- 创建项目
- 创建文件
- 编写代码
- 运行程序
我是在Windows下使用Visual Studio 2019来编写C++程序。
首先我们进行项目的创建:
在点击空项目后,我们进行配置,其中项目名称和位置根据自己的情况设置:
创建好项目后,我们建立C++文件:
然后,我们给源文件命名后进行代码编写:
#include<iostream>
using namespace std;
int main() {
cout << "Hello world" << endl;
system("pause");
return 0;
}
然后我们编译执行:
运行结果:输出Hello world
1.2 变量
作用:给一段指定的内存空间起名,方便操作这段内存
语法:数据类型 变量名 = 初始值;
示例:
#include<iostream>
using namespace std;
int main() {
//变量的定义
//语法:数据类型 变量名 = 初始值
int a = 10;
cout << "a = " << a << endl;
system("pause");
return 0;
}
1.3 常量
作用:用于记录程序中不可更改的数据
C++定义常量两种方式
-
#define 宏常量:
#define 常量名 常量值
通常在文件上方定义,表示一个常量 -
const修饰的变量
const 数据类型 常量名 = 常量值
通常在变量定义前加关键字const,修饰该变量为常量,不可修改
示例:
//1、宏常量
#define day 7
int main() {
cout << "一周里总共有 " << day << " 天" << endl;
//day = 8; //报错,宏常量不可以修改
//2、const修饰变量
const int month = 12;
cout << "一年里总共有 " << month << " 个月份" << endl;
//month = 24; //报错,常量是不可以修改的
system("pause");
return 0;
}
1.4 关键字
作用:关键字是C++中预先保留的单词(标识符)
- 在定义变量或者常量时候,不要用关键字
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 | 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++得关键字,否则会产生歧义。
1.6 标识符命名规则
作用:C++规定给标识符(变量、常量)命名时,有一套自己的规则
- 标识符不能是关键字
- 标识符只能由字母、数字、下划线组成
- 第一个字符必须为字母或下划线
- 标识符中字母区分大小写
建议:给标识符命名时,争取做到见名知意的效果,方便自己和他人的阅读
以上只是简单的介绍一下C++初识内容,有错误的地方欢迎大家指正。