C++ 语言基础与进阶学习教程
本教程覆盖 C++ 学习的各个方面,适合初学者循序渐进地学习。建议在学习过程中多做练习和项目,以加深对理论知识的理解。
第一章:C++ 简介
1.1 C++ 的历史与演变
C++ 由 Bjarne Stroustrup 在 1979 年开始开发,最初被称为 "C with Classes",以扩展 C 语言的功能。1985 年发布了第一个完整版本,随后的标准化过程使其不断演化。C++ 的标准化版本包括 C++98、C++03、C++11、C++14、C++17 和 C++20。
1.2 C++ 的特点和优势
- 面向对象编程:支持封装、继承和多态,提高代码的可重用性。
- 高效性:为系统层面的编程提供了高效的内存管理机制。
- 标准模板库 (STL):包含丰富的算法和数据结构,极大地提高了开发效率。
- 多范式支持:支持过程式、面向对象和泛型编程。
1.3 C++ 的应用领域
- 系统软件:操作系统、编译器和网络系统。
- 应用软件:桌面应用、数据库和图形用户界面。
- 游戏开发:高性能游戏引擎,如 Unreal Engine。
- 嵌入式系统:汽车、家电和机器人设计。
1.4 C++ 的未来展望
随着技术的不断发展,C++ 正在与时俱进,越来越多的特性(如概念和协程)正在被引入,以满足现代开发的需求。社区对于可维护性和安全性的关注也在增加。
第二章:环境搭建
2.1 安装 C++ 编译器与 IDE
Windows
- MinGW:轻量级的编译器,简单易用。
- Visual Studio:功能强大的 IDE,适合 Windows 开发。
Linux
使用命令:sudo apt-get install g++ 或 sudo yum install gcc-c++。
Mac
使用 Homebrew:brew install gcc。
2.2 配置开发环境
确保将编译器添加到系统路径中。可使用命令行工具或终端进行编译和运行。
2.3 编译与运行示例程序
创建一个名为 hello.cpp 的文件,内容如下:
#include <iostream>
using namespace std;
int main() {
cout << "Hello, C++!" << endl;
return 0;
}
在命令行中,使用以下命令编译并运行程序:
g++ hello.cpp -o hello
./hello
第三章:基本语法
3.1 C++ 程序结构
一个基本的 C++ 程序通常包括头文件、主函数和必要的逻辑。
3.2 注释的使用
使用注释可以提高代码的可读性。
// 这是单行注释
/* 这是多行注释
可以跨越多行 */
3.3 数据类型与变量
数据类型
C++ 为程序员提供了种类丰富的内置数据类型和用户自定义的数据类型。下表列出了七种基本的数据类型:
| 类型 | 关键字 |
|---|---|
| 布尔型 | bool |
| 字符型 | char |
| 整型 | int |
| 浮点型 | float |
| 双浮点型 | double |
| 无类型 | void |
| 宽字符型 | wchar_t |
一些基本类型可以使用一个或多个类型修饰符进行修饰:signed, unsigned, short, long。
下表显示了各种变量类型在内存中存储值时需要占用的内存大小及范围(注意:不同系统会有所差异,一字节为 8 位):
| 类型 | 位 | 范围 |
|---|---|---|
| char | 1 个字节 | -128 到 127 或者 0 到 255 |
| unsigned char | 1 个字节 | 0 到 255 |
| signed char | 1 个字节 | -128 到 127 |
| int | 4 个字节 | -2147483648 到 2147483647 |
| unsigned int | 4 个字节 | 0 到 4294967295 |
| short int | 2 个字节 | -32768 到 32767 |
| long int | 8 个字节 | -9,223,372,036,854,775,808 到 9,223,372,036,854,775,807 |
| float | 4 个字节 | +/- 3.4e +/- 38 (~7 个数字) |
| double | 8 个字节 | +/- 1.7e +/- 308 (~15 个数字) |
| long long | 8 个字节 | -9,223,372,036,854,775,807 到 9,223,372,036,854,775,807 |
| long double | 16 个字节 | 长双精度型 16 个字节(128 位) |
| wchar_t | 2 或 4 个字节 | 1 个宽字符 |
注意,各种类型的存储大小与系统位数有关,但目前通用的以 64 位系统为主。
下面实例会输出您电脑上各种数据类型的大小:
#include<iostream>
#include <limits>
using namespace std;
int main() {
cout << "type: \t\t************size**************" << endl;
cout << "bool: \t\t" << "所占字节数:" << sizeof(bool);
cout << "\t最大值:" << numeric_limits<bool>::max();
cout << "\t\t最小值:" << numeric_limits<bool>::min() << endl;
// ... (省略部分输出以保持简洁)
cout << "string: \t" << "所占字节数:" << sizeof(string) << endl;
return 0;
}
变量类型分类
- 整数类型:
int,short,long,long long。 - 浮点类型:
float,double,long double。 - 字符类型:
char,wchar_t,char16_t,char32_t。 - 布尔类型:
bool。 - 枚举类型:
enum。 - 指针类型:
type*。 - 数组类型:
type[]。 - 结构体类型:
struct。 - 类类型:
class。 - 共用体类型:
union。
3.4 常量与输入输出
使用 const 关键字定义常量:
const float gravity = 9.81;
使用 cin 和 cout 进行输入输出:
#include <iostream>
using namespace std;
int main() {
int number;
cout << "请输入一个数字:";
cin >> number;
cout << "你输入的数字是:" << number << endl;
return 0;
}
第四章:控制结构
4.1 条件语句
if 语句示例
int a = 10;
if (a > 0) {
cout << "a 是正数" << endl;
} else {
cout << "a 不是正数" << endl;
}
switch 语句示例
int day = 4;
switch (day) {
case 1: cout << "星期一" << endl; break;
case 2: cout << "星期二" << endl; break;
default: cout << "不是工作日" << endl;
}
4.2 循环结构
for 循环示例
for (int i = 0; i < 5; i++) {
cout << "i 的值:" << i << endl;
}
while 循环示例
int j = 0;
while (j < 5) {
cout << "j 的值:" << j << endl;
j++;
}
do-while 循环示例
int k = 0;
do {
cout << "k 的值:" << k << endl;
k++;
} while (k < 5);
第五章:函数
5.1 函数的定义与调用
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(5, 3);
cout << "5 + 3 = " << result << endl;
return 0;
}
5.2 参数传递方式
- 值传递:将参数的副本传递给函数。
- 引用传递:将参数的引用传递给函数(可以修改原变量)。
- 指针传递:传递变量的地址。
5.3 函数重载
允许同名函数,但参数类型或数量不同。
float multiply(float a, float b) { return a * b; }
int multiply(int a, int b) { return a * b; }
5.4 默认参数与 inline 函数
默认参数示例
void greet(string name = "World") {
cout << "Hello, " << name << "!" << endl;
}
inline 函数示例
inline int square(int x) {
return x * x;
}
5.5 Lambda 表达式与函数对象
使用 lambda 表达式定义简单的函数:
auto add = [](int a, int b) { return a + b; };
cout << "Lambda add: " << add(5, 3) << endl;
第六章:数组与字符串
6.1 一维数组与多维数组
一维数组示例
int arr[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
多维数组示例
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cout << matrix[i][j] << " ";
}
}
6.2 字符串的处理
C++ 字符串使用 std::string:
#include <string>
string str = "Hello, World!";
cout << "字符串长度:" << str.length() << endl;
6.3 常用字符串函数
string str = "Hello";
str += " World";
cout << str << endl;
第七章:指针与引用
7.1 指针的概念与使用
指针是存储变量地址的变量:
int a = 10;
int *p = &a;
cout << "a 的值:" << *p << endl;
7.2 指针与数组的关系
数组名代表数组的首地址,可以用指针访问数组元素:
int arr[3] = {1, 2, 3};
int *p = arr;
cout << *(p + 1) << endl;
7.3 引用的概念与使用
引用是变量的别名:
int b = 20;
int &r = b;
r = 30;
cout << "b 的值:" << b << endl;
7.4 指针与动态内存分配
使用 new 和 delete 进行动态内存管理:
int *ptr = new int;
*ptr = 42;
cout << "动态内存中的值:" << *ptr << endl;
delete ptr;
第八章:结构体与联合体
8.1 结构体的定义与使用
struct Person {
string name;
int age;
};
Person p;
p.name = "Alice";
p.age = 30;
cout << "姓名:" << p.name << ", 年龄:" << p.age << endl;
8.2 结构体数组
Person people[2] = {{"Alice", 30}, {"Bob", 25}};
for (int i = 0; i < 2; i++) {
cout << "姓名:" << people[i].name << ", 年龄:" << people[i].age << endl;
}
8.3 联合体的定义与使用
联合体用于节省内存,所有成员共享相同的内存:
union Data {
int intValue;
float floatValue;
};
Data data;
data.intValue = 10;
cout << "整数值:" << data.intValue << endl;
data.floatValue = 5.5;
cout << "浮点值:" << data.floatValue << endl;
8.4 枚举类型的使用
enum Color { RED, GREEN, BLUE };
Color c = GREEN;
cout << "选择的颜色值:" << c << endl;
第九章:类与对象
9.1 面向对象的基本概念
类是对象的蓝图,对象是类的实例。
9.2 类的定义与对象的创建
class Car {
public:
string brand;
int year;
void display() {
cout << "品牌:" << brand << ", 年份:" << year << endl;
}
};
int main() {
Car myCar;
myCar.brand = "Toyota";
myCar.year = 2020;
myCar.display();
return 0;
}
9.3 构造函数与析构函数
class Point {
public:
int x, y;
Point(int xVal, int yVal) : x(xVal), y(yVal) {}
~Point() {}
};
Point p(10, 20);
9.4 成员函数与属性
class Circle {
public:
double radius;
double area() {
return 3.14 * radius * radius;
}
};
Circle c;
c.radius = 5;
cout << "圆的面积:" << c.area() << endl;
9.5 访问控制
C++ 提供了三种访问控制:public、private、protected。
class Box {
private:
double width;
public:
void setWidth(double w) { width = w; }
double getWidth() { return width; }
};
第十章:继承与多态
10.1 继承的概念与实现
class Animal {
public:
void eat() { cout << "Eating..." << endl; }
};
class Dog : public Animal {
public:
void bark() { cout << "Barking..." << endl; }
};
10.2 基类与派生类
基类提供公共接口,派生类扩展或修改基类的行为。
10.3 虚函数与多态
class Base {
public:
virtual void show() { cout << "Base class" << endl; }
};
class Derived : public Base {
public:
void show() override { cout << "Derived class" << endl; }
};
10.4 多态的实现
通过基类指针调用派生类的重写方法:
Base* basePtr = new Derived();
basePtr->show();
delete basePtr;
第十一章:模板与泛型编程
11.1 函数模板
template <typename T>
T add(T a, T b) {
return a + b;
}
11.2 类模板
template <typename T>
class Pair {
private:
T first, second;
public:
Pair(T a, T b) : first(a), second(b) {}
T getFirst() { return first; }
T getSecond() { return second; }
};
11.3 模板特化
template <>
class Pair<string> {
private:
string first, second;
public:
Pair(string a, string b) : first(a), second(b) {}
string getConcatenated() { return first + second; }
};
11.4 STL(标准模板库)简介
STL 提供了许多通用数据结构和算法,如 vector, list, map, set 等。
#include <vector>
int main() {
vector<int> vec = {1, 2, 3, 4, 5};
for (int num : vec) {
cout << num << " ";
}
return 0;
}
第十二章:异常处理
12.1 异常的概念
异常处理用于处理运行时错误,确保程序的稳定性。
12.2 try, catch, throw 语句
try {
throw runtime_error("发生错误");
} catch (const runtime_error& e) {
cout << "捕获到异常:" << e.what() << endl;
}
12.3 自定义异常类
#include <iostream>
#include <exception>
#include <string>
using namespace std;
class MyException : public std::exception {
private:
string message;
public:
MyException(const string& msg) : message(msg) {}
virtual const char* what() const noexcept override {
return message.c_str();
}
};
void riskyFunction(int value) {
if (value < 0) {
throw MyException("负数错误:不能为负数");
}
}
int main() {
try {
riskyFunction(-1);
} catch (const MyException& e) {
cout << "捕获到异常:" << e.what() << endl;
}
return 0;
}
第十三章:文件操作
13.1 文件的读写操作
示例:写入文件
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream outFile("example.txt");
if (outFile.is_open()) {
outFile << "Hello, file!" << endl;
outFile.close();
}
return 0;
}
示例:读取文件
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream inFile("example.txt");
string line;
if (inFile.is_open()) {
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
}
return 0;
}
13.2 二进制文件与文本文件
示例:写入二进制文件
#include <fstream>
using namespace std;
int main() {
ofstream outFile("binary.dat", ios::binary);
int num = 42;
outFile.write(reinterpret_cast<char*>(&num), sizeof(num));
outFile.close();
return 0;
}
13.3 文件流的使用
#include <fstream>
#include <iostream>
using namespace std;
int main() {
fstream file("example.txt", ios::in | ios::out | ios::app);
if (file.is_open()) {
file << "追加内容!" << endl;
file.seekg(0);
string line;
while (getline(file, line)) {
cout << line << endl;
}
file.close();
}
return 0;
}
第十四章:标准库与命名空间
14.1 C++ 标准库概述
C++ 标准库包含了丰富的函数、类和模板,常用的 STL 组件有容器、算法和迭代器。
14.2 常用标准库函数与算法
示例:使用 vector
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec = {1, 2, 3, 4, 5};
vec.push_back(6);
for (int num : vec) {
cout << num << " ";
}
return 0;
}
示例:使用 algorithm 库
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
vector<int> vec = {5, 3, 1, 4, 2};
sort(vec.begin(), vec.end());
for (int num : vec) {
cout << num << " ";
}
return 0;
}
14.3 命名空间的使用
namespace MyNamespace {
void display() {
cout << "Hello from MyNamespace!" << endl;
}
}
int main() {
MyNamespace::display();
return 0;
}
第十五章:高级特性
15.1 智能指针的使用
示例:使用 std::unique_ptr
#include <iostream>
#include <memory>
using namespace std;
int main() {
unique_ptr<int> ptr(new int(10));
cout << "值:" << *ptr << endl;
return 0;
}
示例:使用 std::shared_ptr
#include <iostream>
#include <memory>
using namespace std;
int main() {
shared_ptr<int> p1(new int(20));
{
shared_ptr<int> p2 = p1;
cout << "值:" << *p2 << endl;
}
cout << "值:" << *p1 << endl;
return 0;
}
15.2 Lambda 表达式与并发编程
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> vec = {1, 2, 3, 4, 5};
for_each(vec.begin(), vec.end(), [](int n) {
cout << n << " ";
});
return 0;
}
15.3 C++11/14/17/20 新特性
- C++11:引入了
auto关键字、范围 for 循环、nullptr、线程库等。 - C++14:改进了 lambda 表达式,支持泛型 lambda。
- C++17:引入了结构化绑定、if constexpr、std::optional 等。
- C++20:引入了概念(concept)、范围(ranges)等。
第十六章:综合项目
16.1 项目设计与结构
设计一个小型项目,定义功能模块与类结构,使用面向对象的设计原则。
16.2 代码实现与管理
使用版本控制工具(如 Git)管理代码,记录每次更新。
16.3 代码调试与优化
使用调试工具(如 GDB 或 IDE 内置调试工具)进行调试,分析性能瓶颈并进行优化。
第十七章:学习资源与实践
17.1 推荐书籍
- 《C++ Primer》 - Stanley B. Lippman
- 《Effective C++》 - Scott Meyers
- 《The C++ Programming Language》 - Bjarne Stroustrup
17.2 在线课程
Coursera、edX、Udacity 等平台的 C++ 课程。
17.3 开源项目与参与
参与 GitHub 上的 C++ 开源项目,学习最佳实践,提升编程能力。
17.4 C++ 社区与论坛
加入 C++ 相关的社区与讨论组(如 Stack Overflow),向他人学习。
第十八章:附录
18.1 C++ 关键字
列出 C++ 中的所有关键字,比如 class, public, private, virtual, template 等。
18.2 常用函数与算法汇总
- 排序:
sort() - 查找:
find() - 复制:
copy() - 变换:
transform()
18.3 参考文献
- C++ 标准文档
- 各大编程网站的相关教程与文档。


