跳到主要内容C++ 语言基础与进阶教程 | 极客日志C++算法
C++ 语言基础与进阶教程
本教程系统讲解 C++ 语言基础语法、控制结构、函数、指针、面向对象编程及标准模板库等核心知识。内容涵盖环境搭建、数据类型、内存管理、文件操作及智能指针等高级特性,并提供代码示例与项目实践建议,适合初学者构建完整的 C++ 知识体系。
狂少1 浏览 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。
下表显示了各种变量类型在内存中存储值时需要占用的内存,以及该类型的变量所能存储的最大值和最小值。
注意,各种类型的存储大小与系统位数有关,但目前通用的以 64 位系统为主。
| 类型 | 位 | 范围 |
|---|
| char | 1 个字节 | -128 到 127 |
| unsigned char | 1 个字节 | 0 到 255 |
| int | 4 个字节 | -2147483648 到 2147483647 |
| unsigned int | 4 个字节 | 0 到 4294967295 |
| long int | 8 个字节 | -9,223,372,036,854,775,808 到 9,223,372,036,854,775,807 |
| float | 4 个字节 | +/- 3.4e +/- 38 |
| double | 8 个字节 | +/- 1.7e +/- 308 |
| long double | 16 个字节 | 长双精度型 |
示例
#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;
}
本实例使用了 endl,这将在每一行后插入一个换行符,<< 运算符用于向屏幕传多个值,sizeof() 运算符用来获取各种数据类型的大小。
基于前一章讲解的基本类型,有以下几种基本的变量类型:
- 整数类型(Integer Types):
int, short, long, long long。
- 浮点类型(Floating-Point Types):
float, double, long double。
- 字符类型(Character Types):
char, wchar_t, char16_t, char32_t。
- 布尔类型(Boolean Type):
bool。
- 枚举类型(Enumeration Types):
enum。
- 指针类型(Pointer Types):
type*。
- 数组类型(Array Types):
type[]。
- 结构体类型(Structure Types):
struct。
- 类类型(Class Types):
class。
- 共用体类型(Union Types):
union。
在 C++ 中,类型的长度取决于编译器和计算机架构,然而,C++ 标准规定了不同整数类型的最小范围。
3.4 常量与输入输出
const float gravity = 9.81;
#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 参数传递方式
- 值传递:将参数的副本传递给函数。
- 引用传递:将参数的引用传递给函数(可以修改原变量)。
- 指针传递:传递变量的地址。
#include <string>
string str = "Hello, World!";
cout << "字符串长度:" << str.length() << endl;
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 表达式与函数对象
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 字符串的处理
引用传递:将参数的引用传递给函数(可以修改原变量)。
void modify(int &num) {
num += 10;
}
int main() {
int x = 5;
modify(x);
cout << "x 的值:" << x << endl;
return 0;
}
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; }
};
int main() {
Dog d;
d.eat();
d.bark();
return 0;
}
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; }
};
int main() {
Base* b = new Derived();
b->show();
delete b;
return 0;
}
10.4 多态的实现
Base* basePtr = new Derived();
basePtr->show();
delete basePtr;
第十一章:模板与泛型编程
11.1 函数模板
template <typename T>
T add(T a, T b) {
return a + b;
}
int main() {
cout << "int: " << add(5, 10) << endl;
cout << "double: " << add(5.5, 3.5) << endl;
return 0;
}
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; }
};
int main() {
Pair<int> p(10, 20);
cout << "First: " << p.getFirst() << ", Second: " << p.getSecond() << endl;
return 0;
}
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; }
};
int main() {
Pair<string> p("Hello", " World");
cout << "Concatenated: " << p.getConcatenated() << endl;
return 0;
}
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 块捕获异常,使用 catch 块处理异常。
try {
throw runtime_error("发生错误");
} catch (const runtime_error& e) {
cout << "捕获到异常:" << e.what() << endl;
}
12.3 自定义异常类
在 C++ 中,你可以根据需要自定义异常类,以提供更具体的错误信息。
示例:定义自定义异常类
#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("负数错误:不能为负数");
}
cout << "输入的值是:" << value << endl;
}
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;
}
示例:读取二进制文件
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream inFile("binary.dat", ios::binary);
int num;
inFile.read(reinterpret_cast<char*>(&num), sizeof(num));
cout << "读取的数:" << num << endl;
inFile.close();
return 0;
}
13.3 文件流的使用
C++ 提供 fstream,用于同时读取和写入文件。
示例
#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 << " ";
}
cout << endl;
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 << " ";
}
cout << endl;
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 表达式与并发编程
Lambda 表达式用于简化函数对象的定义,适合回调和并行执行。
示例:使用 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 << " ";
});
cout << endl;
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
- 《高质量程序设计指南-C++\C 语言》第三版
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 参考文献
相关免费在线工具
- 加密/解密文本
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,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
- JSON 压缩
通过删除不必要的空白来缩小和压缩JSON。 在线工具,JSON 压缩在线工具,online