一、C++语言概述
C++是由丹麦计算机科学家Bjarne Stroustrup于1979年在贝尔实验室开发的一种静态类型、编译式、通用型编程语言。最初被称为"C with Classes"(带类的C),1983年更名为C++。它既具有高级语言的抽象特性,又保留了底层硬件操作能力,被广泛应用于系统软件、应用软件、驱动程序、嵌入式软件、高性能服务器和客户端应用以及娱乐软件等开发领域。
作为C语言的超集,C++引入了面向对象编程(OOP)特性,包括:
- 类与对象
- 封装
- 继承
- 多态
- 抽象
这使得C++成为游戏开发(如Unreal引擎)、系统编程(如操作系统开发)和高性能计算(如金融交易系统)等领域的首选语言。根据TIOBE编程语言排行榜,C++长期保持在前5名最受欢迎的编程语言之列。
二、开发环境搭建
2.1 编译器选择
Windows平台:
- MinGW-w64(推荐): 提供GCC的Windows版本
- Microsoft Visual C++(MSVC): 微软官方编译器
- Clang: 具有优秀的错误提示和编译速度
Linux平台:
- GCC(G++): 大多数Linux发行版默认安装
- Clang: 替代GCC的选择
macOS平台:
- Xcode命令行工具: 包含Clang编译器
- Homebrew安装的GCC
2.2 集成开发环境(IDE)
专业级IDE:
- Visual Studio(Windows): 微软提供的全功能IDE
- CLion(跨平台): JetBrains出品,智能代码补全
- Qt Creator: 特别适合Qt开发
轻量级IDE:
- Code::Blocks: 开源跨平台
- Dev-C++: 简单易用
- Eclipse CDT: 插件丰富
文本编辑器+插件:
- VS Code + C/C++扩展
- Sublime Text + EasyClangComplete
- Atom + ide-cpp
2.3 构建工具
- CMake: 跨平台构建系统
- Makefile: 传统构建工具
- Ninja: 快速构建工具
三、基础语法结构
3.1 第一个C++程序详解
// 预处理指令,引入标准输入输出库
#include <iostream>// 使用标准命名空间,避免每次都要写std::
using namespace std;// 程序入口函数,返回值为int类型
int main() {// cout是标准输出流对象// << 是流插入运算符// "Hello, World!"是字符串常量// endl是换行并刷新缓冲区cout << "Hello, World!" << endl;// 返回0表示程序正常结束return 0;
}
编译运行步骤:
- 保存为hello.cpp
- 命令行执行:
g++ hello.cpp -o hello
- 运行:
./hello
(Linux/macOS)或hello.exe
(Windows)
3.2 数据类型详解
类型 | 说明 | 大小(字节) | 取值范围 | 示例 |
---|---|---|---|---|
int | 整型 | 4 | -2^31 ~ 2^31-1 | int age = 25; |
float | 单精度浮点 | 4 | ±1.18×10^-38 ~ ±3.4×10^38 | float pi = 3.14f; |
double | 双精度浮点 | 8 | ±2.23×10^-308 ~ ±1.79×10^308 | double pi = 3.1415; |
char | 字符 | 1 | -128 ~ 127 | char c = 'A'; |
bool | 布尔值 | 1 | true/false | bool flag = true; |
void | 无类型 | - | - | void func(); |
wchar_t | 宽字符 | 2/4 | 0 ~ 65535 | wchar_t wc = L'中'; |
short | 短整型 | 2 | -32768 ~ 32767 | short s = 100; |
long | 长整型 | 4/8 | 平台相关 | long l = 100000L; |
long long | 长长整型 | 8 | -2^63 ~ 2^63-1 | long long ll = 1LL; |
unsigned | 无符号修饰 | - | 0 ~ 2^n-1 | unsigned int ui; |
四、控制结构
4.1 条件语句扩展
// 基本if语句
if (score >= 60) {cout << "及格" << endl;
}// if-else语句
if (score >= 90) {cout << "优秀" << endl;
} else if (score >= 80) {cout << "良好" << endl;
} else if (score >= 70) {cout << "中等" << endl;
} else if (score >= 60) {cout << "及格" << endl;
} else {cout << "不及格" << endl;
}// 三目运算符(条件运算符)
string result = (score >= 60) ? "及格" : "不及格";// switch语句
switch (grade) {case 'A':cout << "优秀";break;case 'B':cout << "良好";break;case 'C':cout << "及格";break;default:cout << "不及格";
}
4.2 循环结构扩展
// 传统for循环
for (int i = 0; i < 10; i++) {cout << i << " ";
}// 范围for循环(C++11)
vector<int> vec = {1, 2, 3, 4, 5};
for (auto num : vec) {cout << num << " ";
}// while循环
int i = 0;
while (i < 10) {cout << i << " ";i++;
}// do-while循环
int j = 0;
do {cout << j << " ";j++;
} while (j < 10);// 循环控制语句
for (int k = 0; k < 10; k++) {if (k == 5) break; // 跳出循环if (k % 2 == 0) continue; // 跳过本次循环cout << k << " ";
}
五、函数基础
5.1 函数定义详解
// 函数声明(原型)
double calculateCircleArea(double radius);// 函数实现
double calculateCircleArea(double radius) {const double PI = 3.1415926;return PI * radius * radius;
}// 函数调用
double area = calculateCircleArea(5.0);
cout << "圆的面积: " << area << endl;// 默认参数
void printMessage(string msg = "Hello") {cout << msg << endl;
}// 函数重载
void print(int num) {cout << "整数: " << num << endl;
}void print(double num) {cout << "浮点数: " << num << endl;
}void print(string str) {cout << "字符串: " << str << endl;
}
5.2 函数参数传递方式对比
// 1. 值传递(创建副本)
void incrementByValue(int num) {num++; // 不影响原始变量
}// 2. 引用传递(操作原始变量)
void incrementByReference(int &num) {num++; // 修改原始变量
}// 3. 指针传递(通过地址访问)
void incrementByPointer(int *num) {(*num)++; // 解引用后修改
}// 使用示例
int main() {int a = 10;incrementByValue(a);cout << a; // 输出10incrementByReference(a);cout << a; // 输出11incrementByPointer(&a);cout << a; // 输出12return 0;
}
六、面向对象编程
6.1 类与对象详解
// 银行账户类示例
class BankAccount {
private: // 私有成员,外部不可直接访问string accountNumber;string accountHolder;double balance;public: // 公有接口// 构造函数BankAccount(string num, string holder, double bal) : accountNumber(num), accountHolder(holder), balance(bal) {}// 存款方法void deposit(double amount) {if (amount > 0) {balance += amount;cout << "存款成功,当前余额: " << balance << endl;} else {cout << "存款金额必须大于0" << endl;}}// 取款方法bool withdraw(double amount) {if (amount > 0 && amount <= balance) {balance -= amount;cout << "取款成功,当前余额: " << balance << endl;return true;} else {cout << "取款失败,余额不足或金额无效" << endl;return false;}}// 查询余额double getBalance() const {return balance;}// 显示账户信息void display() const {cout << "账户: " << accountNumber << ", 持有人: " << accountHolder<< ", 余额: " << balance << endl;}
};// 使用示例
int main() {BankAccount account("123456789", "张三", 1000.0);account.deposit(500);account.withdraw(200);account.display();return 0;
}
6.2 面向对象三大特性
1. 封装(Encapsulation)
- 将数据和操作数据的方法绑定在一起
- 隐藏对象的内部实现细节
- 通过访问控制实现(public/protected/private)
2. 继承(Inheritance)
- 创建新类(派生类)从现有类(基类)继承特性
- 支持代码重用和层次分类
- 继承方式: public, protected, private
// 基类
class Shape {
protected:int width, height;
public:void setDimensions(int w, int h) {width = w;height = h;}
};// 派生类
class Rectangle : public Shape {
public:int area() {return width * height;}
};// 使用
Rectangle rect;
rect.setDimensions(5, 3);
cout << rect.area(); // 输出15
3. 多态(Polymorphism)
- 同一操作作用于不同对象产生不同行为
- 通过虚函数和继承实现
- 分为编译时多态(函数重载)和运行时多态(虚函数)
class Animal {
public:virtual void makeSound() {cout << "动物发出声音" << endl;}
};class Dog : public Animal {
public:void makeSound() override {cout << "汪汪汪" << endl;}
};class Cat : public Animal {
public:void makeSound() override {cout << "喵喵喵" << endl;}
};// 使用多态
void animalSound(Animal* animal) {animal->makeSound();
}int main() {Animal* animal1 = new Dog();Animal* animal2 = new Cat();animalSound(animal1); // 汪汪汪animalSound(animal2); // 喵喵喵delete animal1;delete animal2;return 0;
}
七、内存管理
7.1 指针深入理解
// 基本指针操作
int var = 42;
int* ptr = &var; // ptr存储var的地址cout << "变量值: " << var << endl; // 42
cout << "指针值: " << ptr << endl; // 0x7ffee3a5a8dc(地址)
cout << "指针指向的值: " << *ptr << endl; // 42// 指针运算
int arr[] = {10, 20, 30};
int* arrPtr = arr; // 指向数组第一个元素cout << *arrPtr << endl; // 10
cout << *(arrPtr + 1) << endl; // 20 (指针移动4字节)// const与指针
int x = 10, y = 20;
const int* ptr1 = &x; // 指针指向常量
ptr1 = &y; // 可以改变指向
// *ptr1 = 30; // 错误:不能修改指向的值int* const ptr2 = &x; // 常量指针
*ptr2 = 30; // 可以修改指向的值
// ptr2 = &y; // 错误:不能改变指向
7.2 动态内存管理
// 单个对象动态分配
int* numPtr = new int(42);
cout << *numPtr << endl; // 42
delete numPtr;// 数组动态分配
int size = 5;
int* arr = new int[size]{1, 2, 3, 4, 5};for (int i = 0; i < size; i++) {cout << arr[i] << " "; // 1 2 3 4 5
}
cout << endl;delete[] arr; // 释放数组内存// 智能指针(C++11)
#include <memory>
unique_ptr<int> uPtr(new int(100));
cout << *uPtr << endl; // 100
// 不需要手动delete,离开作用域自动释放shared_ptr<int> sPtr1 = make_shared<int>(200);
shared_ptr<int> sPtr2 = sPtr1; // 共享所有权
cout << *sPtr1 << " " << *sPtr2 << endl; // 200 200
八、标准模板库(STL)详解
8.1 常用容器对比
容器 | 描述 | 特点 | 适用场景 |
---|---|---|---|
vector | 动态数组 | 随机访问快,尾部操作高效 | 需要频繁随机访问 |
list | 双向链表 | 插入删除高效,不支持随机访问 | 频繁在中间插入删除 |
deque | 双端队列 | 头尾操作高效 | 需要两端操作 |
array | 固定大小数组 | 栈上分配,大小固定 | 需要固定大小容器 |
forward_list | 单向链表 | 更节省空间 | 只需要单向遍历 |
map | 键值对集合(红黑树实现) | 自动排序,查找高效 | 需要键值对且有序 |
unordered_map | 哈希表实现的键值对 | 查找最快,无序 | 需要快速查找不关心顺序 |
set | 唯一元素集合(红黑树) | 自动排序 | 需要唯一元素集合且有序 |
unordered_set | 哈希表实现的唯一元素集合 | 查找最快,无序 | 需要快速查找唯一元素 |
stack | 栈 | LIFO(后进先出) | 需要栈结构 |
queue | 队列 | FIFO(先进先出) | 需要队列结构 |
priority_queue | 优先队列 | 元素按优先级排序 | 需要优先级处理 |
8.2 STL算法示例
#include <algorithm>
#include <vector>
#include <iostream>using namespace std;int main() {vector<int> numbers = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3};// 排序sort(numbers.begin(), numbers.end());// 1 1 2 3 3 4 5 5 6 9// 反转reverse(numbers.begin(), numbers.end());// 9 6 5 5 4 3 3 2 1 1// 查找auto it = find(numbers.begin(), numbers.end(), 5);if (it != numbers.end()) {cout << "找到5,位置: " << distance(numbers.begin(), it) << endl;}// 去重(需要先排序)sort(numbers.begin(), numbers.end());auto last = unique(numbers.begin(), numbers.end());numbers.erase(last, numbers.end());// 1 2 3 4 5 6 9// 遍历并打印for_each(numbers.begin(), numbers.end(), [](int n) {cout << n << " ";});cout << endl;// 统计int countFives = count(numbers.begin(), numbers.end(), 5);cout << "5出现次数: " << countFives << endl;// 最大值/最小值auto minIt = min_element(numbers.begin(), numbers.end());auto maxIt = max_element(numbers.begin(), numbers.end());cout << "最小值: " << *minIt << ", 最大值: " << *maxIt << endl;return 0;
}
九、学习资源推荐
9.1 书籍
入门书籍:
- 《C++ Primer》(第5版): 全面系统,适合深入学习
- 《C++程序设计语言》(Bjarne Stroustrup): C++之父著作
- 《Accelerated C++》: 快速入门实践
进阶书籍:
- 《Effective C++》(Scott Meyers): 55个改善程序的建议
- 《More Effective C++》: 35个进阶建议
- 《Effective Modern C++》: C++11/14特性指南
高级主题:
- 《C++ Templates》: 模板编程权威指南
- 《C++ Concurrency in Action》: 多线程编程
- 《Inside the C++ Object Model》: 对象模型底层实现
9.2 在线资源
参考网站:
- cplusplus.com: 完整参考文档和教程
- cppreference.com: 权威标准库参考
- learncpp.com: 免费互动教程
社区论坛:
- Stack Overflow: 编程问答社区
- Reddit的r/cpp: C++相关讨论
- C++中文网: 国内开发者社区
在线课程:
- Coursera: "C++ For C Programmers"
- Udemy: "Beginning C++ Programming"
- edX: "Introduction to C++"
十、学习建议
-
循序渐进学习路径
- 阶段1: 基础语法、控制结构、函数
- 阶段2: 面向对象编程、模板基础
- 阶段3: 标准库、内存管理、多线程
- 阶段4: 高级特性、设计模式、性能优化
-
实践项目建议
- 简单计算器
- 学生成绩管理系统
- 银行账户模拟
- 简单游戏(如猜数字、井字棋)
- 数据结构实现(链表、栈、队列等)
-
调试技巧
- 学会使用gdb/lldb调试器
- 理解常见编译错误信息
- 使用日志和断点调试
- 学习单元测试框架(Catch2, Google Test)
-
编码规范
- 遵循一致的命名规则
- 合理使用注释
- 保持函数短小单一职责
- 避免全局变量
- 使用const和引用避免拷贝
-
持续学习
- 关注C++标准发展(C++17/20/23)
- 阅读开源项目代码
- 参与开源贡献
- 参加技术会议(CppCon, Meeting C++)
通过系统学习和不断实践,你将能够掌握C++这一强大而灵活的编程语言,开发出高效可靠的软件系统。