1. C++ 简介
C++ 是一种通用的编程语言,支持面向对象、泛型编程等多种编程范式,被广泛用于系统编程、游戏开发、嵌入式系统等领域。
例如,可以使用 C++ 开发一个简单的控制台应用程序来计算两个数的和:
#include
using namespace std;
int main() {
int num1, num2;
cout << "请输入第一个数字: ";
cin >> num1;
cout << "请输入第二个数字: ";
cin >> num2;
int sum = num1 + num2;
cout << "两个数的和是: " << sum << endl;
return 0;
}
公式: sum = num1 + num2
2. 快速入门
编写一个简单的 C++ 程序,输出 "Hello, World!"。
示例代码:
#include
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}
公式: 输出语句:cout << "Hello, World!" << endl;
运行此程序后,控制台将输出 "Hello, World!",这表示程序运行成功。
3. 条件与循环控制
C++ 提供了丰富的控制结构,例如条件语句和循环结构。
- 条件语句:
if
、else
、switch
用于判断条件。 - 循环结构:
for
、while
、do-while
用于重复执行代码块。
示例:
#include
using namespace std;
int main() {
int number;
cout << "请输入一个数字: ";
cin >> number;
if (number > 0) {
cout << "正数" << endl;
} else if (number < 0) {
cout << "负数" << endl;
} else {
cout << "零" << endl;
}
for (int i = 0; i < 5; i++) {
cout << "循环中的 i: " << i << endl;
}
return 0;
}
公式: 条件判断:if (condition) { ... }
4. 函数
C++ 使用函数来组织代码,函数使代码更加模块化、便于复用。
示例:
#include
using namespace std;
int add(int a, int b) {
return a + b;
}
int main() {
int num1 = 5, num2 = 7;
int sum = add(num1, num2);
cout << "两个数的和是: " << sum << endl;
return 0;
}
公式: 函数定义:返回类型 函数名(参数列表) { ... }
5. 面向对象编程 (OOP)
C++ 是一种面向对象的编程语言,支持类与对象、继承、多态等特性。
- 类与对象:类是对象的模板,对象是类的实例。
- 继承:通过继承实现代码复用。
- 多态:不同对象可以以相同方式调用。
示例:
#include
using namespace std;
class Animal {
public:
void sound() {
cout << "Some sound" << endl;
}
};
class Dog : public Animal {
public:
void sound() {
cout << "Woof" << endl;
}
};
int main() {
Animal* myDog = new Dog();
myDog->sound(); // 输出 "Woof"
delete myDog;
return 0;
}
公式: 继承:class SubClass : public SuperClass
公式: 多态:SuperClass* obj = new SubClass()
6. 指针与引用
C++ 支持指针和引用,指针用于存储内存地址,引用是变量的别名。
示例:
#include
using namespace std;
int main() {
int num = 10;
int* ptr = #
int& ref = num;
cout << "num 的值: " << num << endl;
cout << "指针 ptr 指向的值: " << *ptr << endl;
cout << "引用 ref 的值: " << ref << endl;
return 0;
}
公式: 指针:Type* ptr = &variable
公式: 引用:Type& ref = variable
7. 模板
C++ 模板使函数和类可以处理任意类型的数据,提高代码的复用性。
示例:
#include
using namespace std;
template
T add(T a, T b) {
return a + b;
}
int main() {
cout << "整数相加: " << add(3, 4) << endl;
cout << "浮点数相加: " << add(3.5, 4.2) << endl;
return 0;
}
公式: 模板定义:template <typename T> 返回类型 函数名(参数列表) { ... }
8. 异常处理
异常处理用于捕获和处理程序中的错误或异常情况。
示例:
#include
using namespace std;
int main() {
try {
int a = 10;
int b = 0;
if (b == 0) {
throw runtime_error("除以零错误");
}
int c = a / b;
} catch (const runtime_error& e) {
cout << "捕获异常: " << e.what() << endl;
}
return 0;
}
公式: 异常处理:try { ... } catch (ExceptionType& e) { ... }
9. 文件操作
C++ 提供了 fstream
库来进行文件读写操作。
示例:
#include
#include
using namespace std;
int main() {
ofstream outFile("example.txt");
if (outFile.is_open()) {
outFile << "这是写入文件的内容" << endl;
outFile.close();
}
ifstream inFile("example.txt");
string line;
if (inFile.is_open()) {
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
}
return 0;
}
公式: 文件操作:ofstream/ofstream 对象; ifstream 对象
10. 标准模板库 (STL)
STL 提供了丰富的数据结构和算法,如向量 (vector
)、链表 (list
)、集合 (set
) 等。
示例:
#include
#include
#include
using namespace std;
int main() {
vector vec = {1, 2, 3, 4, 5};
for (int val : vec) {
cout << "向量值: " << val << endl;
}
set mySet;
mySet.insert(10);
mySet.insert(20);
mySet.insert(10); // 重复值不会被添加
for (int val : mySet) {
cout << "集合中的值: " << val << endl;
}
return 0;
}
公式: 向量声明:vector<Type> vec = {...}
公式: 集合插入:set<Type> mySet; mySet.insert(value);
11. 内存管理与智能指针
C++ 允许手动管理内存,通过 new
和 delete
进行动态内存分配,但这容易导致内存泄漏。智能指针是 C++11 引入的工具,用于自动管理内存。
- unique_ptr:表示唯一拥有某对象的智能指针。
- shared_ptr:多个智能指针可以共享同一个对象。
- weak_ptr:解决
shared_ptr
之间的循环引用问题。
示例:
#include
#include
using namespace std;
int main() {
unique_ptr p1 = make_unique(10);
cout << "unique_ptr 的值: " << *p1 << endl;
shared_ptr p2 = make_shared(20);
shared_ptr p3 = p2;
cout << "shared_ptr 的值: " << *p2 << " 和 " << *p3 << endl;
return 0;
}
公式: 创建智能指针:unique_ptr
12. 并发与多线程编程
C++11 引入了多线程支持,可以使用 thread
类创建线程来实现并发。
- thread:用于创建新线程。
- mutex:互斥锁,用于保护共享资源。
- condition_variable:用于线程间的同步。
示例:
#include
#include
#include
using namespace std;
mutex mtx;
void printThread(int id) {
lock_guard guard(mtx);
cout << "线程 " << id << " 正在运行" << endl;
}
int main() {
thread t1(printThread, 1);
thread t2(printThread, 2);
t1.join();
t2.join();
return 0;
}
公式: 创建线程:thread t(function, args...);
13. C++11/14/17/20 新特性
C++11 及后续标准引入了许多新特性,如右值引用、lambda 表达式、constexpr、结构化绑定等。
- 右值引用:通过
&&
表示,用于实现移动语义,减少不必要的拷贝。 - lambda 表达式:用于定义匿名函数,简化代码。
- constexpr:用于编译时常量计算。
- 结构化绑定 (C++17):允许解构对象。
示例:
#include
using namespace std;
int main() {
auto lambda = [](int x, int y) { return x + y; };
cout << "Lambda 结果: " << lambda(5, 3) << endl;
constexpr int val = 10;
cout << "constexpr 值: " << val << endl;
pair p = {1, "Hello"};
auto [num, text] = p;
cout << "结构化绑定: " << num << ", " << text << endl;
return 0;
}
公式: lambda 表达式:auto lambda = [](parameters) { body };
14. 网络编程与套接字
C++ 可以通过 boost.asio
或 POSIX 套接字实现网络编程,用于客户端与服务器的通信。
示例(简单的套接字服务器):
#include
#include
#include
#include
using namespace std;
int main() {
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(8080);
bind(server_fd, (struct sockaddr*)&address, sizeof(address));
listen(server_fd, 3);
cout << "服务器已启动,等待连接..." << endl;
int client_socket = accept(server_fd, nullptr, nullptr);
cout << "客户端已连接" << endl;
close(client_socket);
close(server_fd);
return 0;
}
公式: 创建套接字:int socket(int domain, int type, int protocol);
15. 模板元编程
模板元编程(Template Metaprogramming, TMP)是一种在编译期生成代码的方法,通过递归模板实现复杂的编译期逻辑。
示例(阶乘计算):
#include
using namespace std;
template
struct Factorial {
static const int value = N * Factorial::value;
};
template<>
struct Factorial<0> {
static const int value = 1;
};
int main() {
cout << "5 的阶乘是: " << Factorial<5>::value << endl;
return 0;
}
公式: 模板递归:template<int N> struct StructName { ... };
16. CMake 使用
CMake 是一个跨平台的构建系统,可以用于生成编译项目所需的文件。
示例(CMakeLists.txt):
cmake_minimum_required(VERSION 3.10)
project(MyProject)
set(CMAKE_CXX_STANDARD 17)
add_executable(MyExecutable main.cpp)
公式: 设置 C++ 标准:set(CMAKE_CXX_STANDARD 17)
17. C++ 标准库详细解析
C++ 标准库提供了丰富的功能,如算法、容器、迭代器等。
- 算法:
std::sort
、std::find
等。 - 容器:
vector
、map
、set
等。 - 迭代器:用于遍历容器的元素。
示例:
#include
#include
#include
using namespace std;
int main() {
vector vec = {5, 1, 4, 2, 3};
sort(vec.begin(), vec.end());
for (int val : vec) {
cout << val << " ";
}
cout << endl;
return 0;
}
公式: 排序算法:std::sort(container.begin(), container.end());