一、基础语法:程序的骨架
1.1 第一个 C++ 程序
{
std::cout << << std::endl;
;
}
C++ 是一门融合了面向过程、面向对象和泛型编程的多范式语言,广泛应用于系统开发、游戏引擎等领域。系统梳理了 C++ 的核心知识点,涵盖基础语法、控制流、函数封装、数组与字符串、面向对象特性(类、继承、多态)、STL 容器及异常处理。每个概念均配有可运行的代码示例,帮助初学者快速掌握从入门到进阶的学习路径。

{
std::cout << << std::endl;
;
}
编译运行:使用 g++ 编译:g++ hello.cpp -o hello,执行 ./hello 输出 Hello, C++!。
核心说明:
#include <iostream>:引入标准输入输出库,必须包含才能使用 cout。std::cout:标准输出对象,std 是命名空间(避免命名冲突)。main():程序唯一入口,返回 0 表示成功,非 0 表示异常。C++ 是强类型语言,变量必须先声明类型再使用,基本数据类型如下:
| 类型 | 说明 | 示例 |
|---|---|---|
int | 整数(4 字节) | int age = 20; |
float | 单精度浮点数(4 字节) | float pi = 3.14f; |
double | 双精度浮点数(8 字节) | double salary = 5000.5; |
char | 字符(1 字节) | char grade = 'A'; |
bool | 布尔值(true/false) | bool isStudent = true; |
示例:
#include <iostream>
using namespace std; // 简化代码,可直接使用 cout 而非 std::cout
int main() {
int a = 10;
double b = 3.14159;
char c = 'Z';
bool d = false;
cout << "整数:" << a << endl;
cout << "浮点数:" << b << endl;
cout << "字符:" << c << endl;
cout << "布尔值(1=true,0=false):" << d << endl; // 输出 0
return 0;
}
const 声明。* 访问指向的值,通过 & 获取变量地址。示例:
#include <iostream>
using namespace std;
int main() {
// 常量:值不可修改
const int MAX_AGE = 120;
// MAX_AGE = 130; // 编译错误:常量不能赋值
// 指针示例
int num = 100;
int* p = # // p 是指向 int 的指针,存储 num 的地址
cout << "num 的值:" << num << endl; // 100
cout << "num 的地址:" << &num << endl; // 0x7ffd...(地址值)
cout << "指针 p 存储的地址:" << p << endl; // 与&num 相同
cout << "指针 p 指向的值:" << *p << endl; // 100(通过*访问值)
*p = 200; // 通过指针修改 num 的值
cout << "修改后 num 的值:" << num << endl; // 200
return 0;
}
#include <iostream>
using namespace std;
int main() {
// if-else 语句
int score = 85;
if (score >= 90) {
cout << "优秀" << endl;
} else if (score >= 60) {
cout << "及格" << endl; // 输出此句
} else {
cout << "不及格" << endl;
}
// switch 语句(适合多条件判断)
char grade = 'B';
switch (grade) {
case 'A': cout << "90-100 分"; break;
case 'B': cout << "80-89 分"; break; // 输出此句
case 'C': cout << "60-79 分"; break;
default: cout << "不及格";
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
// for 循环:输出 1-5
cout << "for 循环:";
for (int i = 1; i <= 5; i++) {
cout << i << " "; // 输出:1 2 3 4 5
}
cout << endl;
// while 循环:计算 1+2+...+10
cout << "while 循环求和:";
int sum = 0, n = 1;
while (n <= 10) {
sum += n;
n++;
}
cout << sum << endl; // 输出:55
// do-while 循环:至少执行一次
cout << "do-while 循环:";
int m = 1;
do {
cout << m << " "; // 输出:1
m++;
} while (m < 1); // 条件不成立,但仍执行一次
return 0;
}
#include <iostream>
using namespace std;
int main() {
// break:跳出循环
cout << "break 示例:";
for (int i = 1; i <= 10; i++) {
if (i == 5) break; // i=5 时跳出循环
cout << i << " "; // 输出:1 2 3 4
}
cout << endl;
// continue:跳过本次循环剩余部分
cout << "continue 示例:";
for (int i = 1; i <= 5; i++) {
if (i == 3) continue; // i=3 时跳过后续代码
cout << i << " "; // 输出:1 2 4 5
}
return 0; // 结束函数
}
函数由'返回类型、函数名、参数列表、函数体'组成,用于封装特定功能。
#include <iostream>
using namespace std;
// 函数定义:计算两数之和
int add(int a, int b) {
// a 和 b 是参数
return a + b; // 返回计算结果
}
// 函数定义:无返回值(void)
void printHello() {
cout << "Hello from function!" << endl;
}
int main() {
printHello(); // 调用无参函数
int x = 10, y = 20;
int result = add(x, y); // 调用有参函数,传入 x 和 y
cout << "10 + 20 = " << result << endl; // 30
return 0;
}
C++ 允许同一作用域内定义多个同名函数,只要参数列表(类型 / 数量 / 顺序)不同。
#include <iostream>
using namespace std;
// 重载 1:两个 int 相加
int add(int a, int b) {
return a + b;
}
// 重载 2:三个 int 相加(参数数量不同)
int add(int a, int b, int c) {
return a + b + c;
}
// 重载 3:两个 double 相加(参数类型不同)
double add(double a, double b) {
return a + b;
}
int main() {
cout << add(1, 2) << endl; // 3(调用重载 1)
cout << add(1, 2, 3) << endl; // 6(调用重载 2)
cout << add(1.5, 2.5) << endl; // 4.0(调用重载 3)
return 0;
}
递归是解决分治问题的常用方法(如阶乘、斐波那契数列)。
#include <iostream>
using namespace std;
// 递归计算 n 的阶乘(n! = n*(n-1)*...*1)
int factorial(int n) {
if (n == 1) return 1; // 终止条件:1! = 1
return n * factorial(n - 1); // 递归调用:n! = n*(n-1)!
}
int main() {
cout << "5 的阶乘:" << factorial(5) << endl; // 120
return 0;
}
#include <iostream>
using namespace std;
int main() {
// 定义数组:类型 数组名 [长度] = {元素};
int numbers[5] = {10, 20, 30, 40, 50}; // 长度为 5 的 int 数组
// 访问数组元素(下标从 0 开始)
cout << "第 3 个元素:" << numbers[2] << endl; // 30
// 遍历数组(计算总和)
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += numbers[i];
}
cout << "数组总和:" << sum << endl; // 150
// 二维数组(行×列)
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
cout << "二维数组 [1][2]:" << matrix[1][2] << endl; // 6
return 0;
}
� 结尾的字符数组(如 char str[] = "hello")。string 类(需包含 <string>,支持动态长度和丰富操作)。#include <iostream>
#include <string> // 必须包含才能使用 string 类
using namespace std;
int main() {
// C 风格字符串
char cStr[] = "Hello";
cout << "C 风格字符串:" << cStr << endl; // Hello
// C++ string 类(更易用)
string cppStr = "World";
cout << "C++ 字符串:" << cppStr << endl; // World
// string 拼接
string fullStr = cStr + " " + cppStr;
cout << "拼接结果:" << fullStr << endl; // Hello World
// string 长度
cout << "长度:" << fullStr.size() << endl; // 11(含空格)
// 字符串比较(按字典序)
if (cppStr == "World") {
cout << "字符串相等" << endl;
}
return 0;
}
类是'数据(成员变量)+ 操作(成员函数)'的封装,对象是类的实例。
#include <iostream>
#include <string>
using namespace std;
// 定义类:描述"学生"
class Student {
private:
// 私有成员(仅类内可访问)
string name;
int age;
public:
// 公有成员(类外可访问)
// 构造函数:创建对象时初始化(与类名相同,无返回值)
Student(string n, int a) {
name = n;
age = a;
}
// 成员函数:获取姓名
string getName() {
return name;
}
// 成员函数:设置年龄(带验证)
void setAge(int a) {
if (a > 0 && a < 150) {
age = a;
}
}
// 成员函数:打印信息
void printInfo() {
cout << "姓名:" << name << ",年龄:" << age << endl;
}
};
int main() {
// 创建对象(调用构造函数)
Student s("张三", 20);
s.printInfo(); // 姓名:张三,年龄:20
// 调用公有成员函数
s.setAge(21);
cout << "修改后姓名:" << s.getName() << endl; // 张三
s.printInfo(); // 姓名:张三,年龄:21
return 0;
}
子类继承父类的属性和方法,并可添加新功能或重写父类方法。
#include <iostream>
using namespace std;
// 父类:Person
class Person {
protected:
// 保护成员(子类可访问,类外不可)
string name;
int age;
public:
Person(string n, int a) : name(n), age(a) {}
void printBaseInfo() {
cout << "姓名:" << name << ",年龄:" << age << endl;
}
};
// 子类:Student(继承 Person)
class Student : public Person {
private:
int id; // 子类新增成员
public:
// 子类构造函数:先调用父类构造函数
Student(string n, int a, int i) : Person(n, a), id(i) {}
// 子类新增方法
void printStudentInfo() {
printBaseInfo(); // 调用父类方法
cout << "学号:" << id << endl;
}
};
int main() {
Student s("李四", 18, 10001);
s.printStudentInfo(); // 输出:
// 姓名:李四,年龄:18
// 学号:10001
return 0;
}
通过'虚函数'实现多态:父类指针指向子类对象时,调用的是子类重写的方法。
#include <iostream>
using namespace std;
// 父类:Shape(形状)
class Shape {
public:
// 虚函数:可被子类重写
virtual double getArea() {
return 0; // 基类默认实现
}
};
// 子类:Circle(圆)
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
// 重写父类虚函数
double getArea() override {
return 3.14 * radius * radius; // 圆面积=πr²
}
};
// 子类:Rectangle(矩形)
class Rectangle : public Shape {
private:
double width, height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
// 重写父类虚函数
double getArea() override {
return width * height; // 矩形面积=长×宽
}
};
int main() {
Shape* shape1 = new Circle(2); // 父类指针指向 Circle 对象
Shape* shape2 = new Rectangle(3, 4); // 父类指针指向 Rectangle 对象
cout << "圆面积:" << shape1->getArea() << endl; // 12.56
cout << "矩形面积:" << shape2->getArea() << endl; // 12
delete shape1; // 释放内存
delete shape2;
return 0;
}
STL(Standard Template Library)提供了常用数据结构(容器)和算法,无需重复造轮子。
#include <iostream>
#include <vector> // 包含 vector
using namespace std;
int main() {
// 创建 vector(初始为空)
vector<int> nums;
// 添加元素
nums.push_back(10);
nums.push_back(20);
nums.push_back(30);
// 访问元素(类似数组)
cout << "第二个元素:" << nums[1] << endl; // 20
// 遍历 vector(用迭代器)
cout << "所有元素:";
for (vector<int>::iterator it = nums.begin(); it != nums.end(); it++) {
cout << *it << " "; // 10 20 30
}
cout << endl;
// 大小与清空
cout << "元素个数:" << nums.size() << endl; // 3
nums.clear();
cout << "清空后个数:" << nums.size() << endl; // 0
return 0;
}
#include <iostream>
#include <map> // 包含 map
using namespace std;
int main() {
// 创建 map(键为 string,值为 int)
map<string, int> scoreMap;
// 添加键值对
scoreMap["张三"] = 90;
scoreMap["李四"] = 85;
scoreMap["王五"] = 95;
// 访问值
cout << "张三的分数:" << scoreMap["张三"] << endl; // 90
// 遍历 map(用迭代器)
cout << "所有分数:" << endl;
for (map<string, int>::iterator it = scoreMap.begin(); it != scoreMap.end(); it++) {
// it->first 是键,it->second 是值
cout << it->first << ":" << it->second << endl;
}
// 输出按键排序:李四:85 王五:95 张三:90
return 0;
}
通过 try-catch 捕获并处理异常,避免程序崩溃。
#include <iostream>
using namespace std;
// 除法函数:除数为 0 时抛出异常
double divide(int a, int b) {
if (b == 0) {
// 抛出异常(可以是任意类型,这里用 string)
throw string("错误:除数不能为 0!");
}
return (double)a / b;
}
int main() {
int x = 10, y = 0;
try {
// 可能抛出异常的代码
double result = divide(x, y);
cout << "结果:" << result << endl; // 此句不会执行
} catch (string errorMsg) {
// 捕获并处理异常
cout << "捕获到异常:" << errorMsg << endl; // 输出错误信息
}
return 0;
}
C++ 的灵活性带来了学习难度,但也使其成为'接近系统底层'的强大工具。多写代码、调试报错、阅读开源项目(如 STL 源码)是提升的关键。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online
通过删除不必要的空白来缩小和压缩JSON。 在线工具,JSON 压缩在线工具,online