目录

C++ 基础入门

本章节主要介绍 C++ 的基础语法知识,帮助初学者编写第一个 C++ 程序。

1. C++ 初识

1.1 第一个 C++ 程序

编写一个 C++ 程序总共分为 4 个步骤:

  1. 创建项目
  2. 创建文件
  3. 编写代码
  4. 运行程序

1.1.1 创建项目

Visual Studio 是我们用来编写 C++ 程序的主要工具,我们先将它打开。

1.1.2 创建文件

右键源文件,选择 添加 → 新建项。给 C++ 文件起个名称,然后点击添加即可。

1.1.3 编写代码

C++ 的标准代码结构如下:

#include <iostream> 
using namespace std;
 
int main() {
 
    cout << "Hello world" << endl;
 
    system("pause");
 
    return 0;
}

1.1.4 运行程序

点击运行按钮或使用快捷键,程序将输出结果。


1.2 注释

作用:在代码中加一些说明和解释,方便自己或其他程序员阅读代码。

两种格式

语法:

// 描述信息

说明:通常放在一行代码的上方,或者一条语句的末尾,对该行代码说明

提示:编译器在编译代码时,会忽略注释的内容。

1.3 变量

作用:给一段指定的内存空间起名,方便操作这段内存。

语法数据类型 变量名 = 初始值;

示例

#include <iostream>
using namespace std;
 
int main() {
 
    // 变量的定义
    // 语法:数据类型 变量名 = 初始值
    int a = 10;
 
    cout << "a = " << a << endl;
 
    system("pause");
 
    return 0;
}

1.4 常量

作用:用于记录程序中不可更改的数据。

C++ 定义常量有两种方式:

  1. #define 宏常量
    • 语法:#define 常量名 常量值
    • 说明:通常在文件上方定义,表示一个常量。
  2. const 修饰的变量
    • 语法:const 数据类型 常量名 = 常量值
    • 说明:通常在变量定义前加关键字 const,修饰该变量为常量,不可修改。

示例

#include <iostream>
using namespace std;
 
// 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.5 关键字

作用:关键字是 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++ 规定给标识符(变量、常量)命名时,有一套自己的规则。

建议:给标识符命名时,争取做到见名知意的效果,方便自己和他人的阅读。