跳到主要内容C++ 编程基础与进阶实战指南 | 极客日志C++算法
C++ 编程基础与进阶实战指南
C++ 语言涵盖从基础语法到高级特性的完整知识体系。内容包含环境搭建、数据类型、控制流、函数、内存管理、面向对象编程及标准库应用。通过实例代码演示指针、智能指针、STL 容器等核心概念,适合初学者系统掌握并应用于实际项目开发。
remedios1 浏览 C++ 编程基础与进阶实战指南
本教程旨在帮助初学者系统掌握 C++ 语言的核心概念,从环境搭建到高级特性,结合实例代码演示关键知识点。建议在学习过程中多动手实践,通过项目巩固理论。
第一章:C++ 简介
1.1 C++ 的历史与演变
C++ 由 Bjarne Stroustrup 于 1979 年开始开发,最初名为 "C with Classes",旨在扩展 C 语言的功能。1985 年发布首个完整版本,随后经历了多次标准化迭代,包括 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:功能强大的集成开发环境,推荐用于大型项目。
Linux
使用包管理器安装 GCC 编译器:
sudo apt-get install g++
sudo yum install gcc-c++
Mac
推荐使用 Homebrew:
brew install gcc
2.2 配置开发环境
确保编译器路径已添加到系统环境变量中,以便在终端直接调用 g++ 等命令。
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++ 程序通常包含头文件引用、命名空间声明、主函数 main() 以及业务逻辑。
3.2 注释的使用
3.3 数据类型与变量
C++ 提供了丰富的内置类型。下表列出了常见的基本类型及其典型大小(基于 64 位系统):
| 类型 | 关键字 | 说明 |
|---|
| 布尔型 | bool | true 或 false |
| 字符型 | char | ASCII 字符 |
| 整型 | int | 整数 |
| 浮点型 | float | 单精度浮点数 |
| 双浮点型 | double | 双精度浮点数 |
| 宽字符型 | wchar_t | 宽字符 |
注意:具体字节数取决于编译器和架构,但现代系统通常遵循上述规律。
示例:查看类型大小
#include <iostream>
#include <limits>
using namespace std;
int main() {
cout << "bool size: " << sizeof(bool) << endl;
cout << "int size: " << sizeof(int) << endl;
cout << "double size: " << sizeof(double) << endl;
return 0;
}
3.4 常量与输入输出
使用 const 定义常量,cin/cout 处理交互:
#include <iostream>
using namespace std;
int main() {
const float gravity = 9.81;
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 参数传递方式
- 值传递:传递副本,函数内修改不影响原变量。
- 引用传递:传递别名,函数内修改直接影响原变量。
void modify(int &num) {
num += 10;
}
int main() {
int x = 5;
modify(x);
cout << "x 的值:" << x << endl;
return 0;
}
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 int square(int x) {
return x * x;
}
5.5 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 而非 C 风格字符串:
#include <string>
string str = "Hello, World!";
cout << "长度:" << str.length() << endl;
6.3 常用字符串函数
string s1 = "Hello";
s1 += " World";
cout << s1 << 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 指针与动态内存分配
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;
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;
data.floatValue = 5.5;
8.4 枚举类型的使用
enum Color { RED, GREEN, BLUE };
Color c = GREEN;
第九章:类与对象
9.1 面向对象的基本概念
9.2 类的定义与对象的创建
class Car {
public:
string brand;
int year;
void display() {
cout << "品牌:" << brand << ", 年份:" << year << endl;
}
};
Car myCar;
myCar.brand = "Toyota";
myCar.year = 2020;
myCar.display();
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 访问控制
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; }
};
Dog d;
d.eat();
d.bark();
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; }
};
Base* b = new Derived();
b->show();
delete b;
10.4 多态的实现
第十一章:模板与泛型编程
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) {}
};
11.3 模板特化
11.4 STL(标准模板库)简介
#include <vector>
vector<int> vec = {1, 2, 3, 4, 5};
for (int num : vec) {
cout << num << " ";
}
第十二章:异常处理
12.1 异常的概念
12.2 try, catch, throw 语句
try {
throw runtime_error("发生错误");
} catch (const runtime_error& e) {
cout << "捕获到异常:" << e.what() << endl;
}
12.3 自定义异常类
继承自 std::exception 并重写 what() 方法:
#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>
ofstream outFile("example.txt");
outFile << "Hello, file!" << endl;
outFile.close();
读取文件
ifstream inFile("example.txt");
string line;
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
13.2 二进制文件与文本文件
ofstream outFile("binary.dat", ios::binary);
int num = 42;
outFile.write(reinterpret_cast<char*>(&num), sizeof(num));
outFile.close();
13.3 文件流的使用
fstream file("example.txt", ios::in | ios::out | ios::app);
file << "追加内容!" << endl;
file.close();
第十四章:标准库与命名空间
14.1 C++ 标准库概述
14.2 常用标准库函数与算法
使用 vector
#include <vector>
vector<int> vec = {1, 2, 3};
vec.push_back(4);
使用 algorithm 库
#include <algorithm>
sort(vec.begin(), vec.end());
14.3 命名空间的使用
namespace MyNamespace {
void display() {
cout << "Hello from MyNamespace!" << endl;
}
}
MyNamespace::display();
第十五章:高级特性
15.1 智能指针的使用
unique_ptr
#include <memory>
unique_ptr<int> ptr(new int(10));
shared_ptr
shared_ptr<int> p1(new int(20));
shared_ptr<int> p2 = p1;
15.2 Lambda 表达式与并发编程
#include <algorithm>
vector<int> vec = {1, 2, 3};
for_each(vec.begin(), vec.end(), [](int n) {
cout << n << " ";
});
15.3 C++11/14/17/20 新特性
- C++11:auto, nullptr, 线程库。
- C++14:泛型 Lambda。
- C++17:结构化绑定,optional。
- C++20:Concepts, Ranges。
第十六章:综合项目
16.1 项目设计与结构
16.2 代码实现与管理
16.3 代码调试与优化
第十七章:学习资源与实践
17.1 推荐书籍
- 《C++ Primer》
- 《Effective C++》
- 《The C++ Programming Language》
17.2 在线课程
17.3 开源项目与参与
17.4 C++ 社区与论坛
Stack Overflow、Reddit C++ 版块等。
第十八章:附录
18.1 C++ 关键字
class, public, private, virtual, template 等。
18.2 常用函数与算法汇总
排序 sort()、查找 find()、复制 copy() 等。
18.3 参考文献
相关免费在线工具
- 加密/解密文本
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
- Gemini 图片去水印
基于开源反向 Alpha 混合算法去除 Gemini/Nano Banana 图片水印,支持批量处理与下载。 在线工具,Gemini 图片去水印在线工具,online
- Base64 字符串编码/解码
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
- Base64 文件转换器
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
- Markdown转HTML
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online
- HTML转Markdown
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online