C++ 语言基础与进阶学习教程
本教程覆盖 C++ 学习的各个方面,适合初学者循序渐进地学习。建议在学习过程中多做练习和项目,以加深对理论知识的理解。
C++ 语言基础与进阶学习教程涵盖从环境搭建、基本语法到面向对象编程、模板及标准库的完整知识体系。内容包含数据类型、控制结构、函数、指针、类与对象、继承多态等核心概念,并提供大量代码示例。教程还涉及异常处理、文件操作、智能指针及 C++11/14/17/20 新特性,适合初学者系统掌握 C++ 开发技能。

本教程覆盖 C++ 学习的各个方面,适合初学者循序渐进地学习。建议在学习过程中多做练习和项目,以加深对理论知识的理解。
C++ 由 Bjarne Stroustrup 在 1979 年开始开发,最初被称为 "C with Classes",以扩展 C 语言的功能。1985 年发布了第一个完整版本,随后的标准化过程使其不断演化。C++ 的标准化版本包括 C++98、C++03、C++11、C++14、C++17 和 C++20。
随着技术的不断发展,C++ 正在与时俱进,越来越多的特性(如概念和协程)正在被引入,以满足现代开发的需求。社区对于可维护性和安全性的关注也在增加。
使用命令:sudo apt-get install g++ 或 sudo yum install gcc-c++。
使用 Homebrew:brew install gcc。
确保将编译器添加到系统路径中。可使用命令行工具或终端进行编译和运行。
创建一个名为 hello.cpp 的文件,内容如下:
#include <iostream>
using namespace std;
int main() {
cout << "Hello, C++!" << endl;
return 0;
}
在命令行中,使用以下命令编译并运行程序:
g++ hello.cpp -o hello
./hello
一个基本的 C++ 程序通常包括头文件、主函数和必要的逻辑。
使用注释可以提高代码的可读性。
// 这是单行注释
/* 这是多行注释
可以跨越多行 */
数据类型
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。使用 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;
}
int a = 10;
if (a > 0) {
cout << "a 是正数" << endl;
} else {
cout << "a 不是正数" << endl;
}
int day = 4;
switch (day) {
case 1: cout << "星期一" << endl; break;
case 2: cout << "星期二" << endl; break;
default: cout << "不是工作日" << endl;
}
for (int i = 0; i < 5; i++) {
cout << "i 的值:" << i << endl;
}
int j = 0;
while (j < 5) {
cout << "j 的值:" << j << endl;
j++;
}
int k = 0;
do {
cout << "k 的值:" << k << endl;
k++;
} while (k < 5);
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(5, 3);
cout << "5 + 3 = " << result << endl;
return 0;
}
允许同名函数,但参数类型或数量不同。
float multiply(float a, float b) { return a * b; }
int multiply(int a, int b) { return a * b; }
void greet(string name = "World") {
cout << "Hello, " << name << "!" << endl;
}
inline int square(int x) {
return x * x;
}
使用 lambda 表达式定义简单的函数:
auto add = [](int a, int b) { return a + b; };
cout << "Lambda add: " << add(5, 3) << endl;
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] << " ";
}
}
C++ 字符串使用 std::string:
#include <string>
string str = "Hello, World!";
cout << "字符串长度:" << str.length() << endl;
string str = "Hello";
str += " World";
cout << str << endl;
指针是存储变量地址的变量:
int a = 10;
int *p = &a;
cout << "a 的值:" << *p << endl;
数组名代表数组的首地址,可以用指针访问数组元素:
int arr[3] = {1, 2, 3};
int *p = arr;
cout << *(p + 1) << endl;
引用是变量的别名:
int b = 20;
int &r = b;
r = 30;
cout << "b 的值:" << b << endl;
使用 new 和 delete 进行动态内存管理:
int *ptr = new int;
*ptr = 42;
cout << "动态内存中的值:" << *ptr << endl;
delete ptr;
struct Person {
string name;
int age;
};
Person p;
p.name = "Alice";
p.age = 30;
cout << "姓名:" << p.name << ", 年龄:" << p.age << endl;
Person people[2] = {{"Alice", 30}, {"Bob", 25}};
for (int i = 0; i < 2; i++) {
cout << "姓名:" << people[i].name << ", 年龄:" << people[i].age << endl;
}
联合体用于节省内存,所有成员共享相同的内存:
union Data {
int intValue;
float floatValue;
};
Data data;
data.intValue = 10;
cout << "整数值:" << data.intValue << endl;
data.floatValue = 5.5;
cout << "浮点值:" << data.floatValue << endl;
enum Color { RED, GREEN, BLUE };
Color c = GREEN;
cout << "选择的颜色值:" << c << endl;
类是对象的蓝图,对象是类的实例。
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;
}
class Point {
public:
int x, y;
Point(int xVal, int yVal) : x(xVal), y(yVal) {}
~Point() {}
};
Point p(10, 20);
class Circle {
public:
double radius;
double area() {
return 3.14 * radius * radius;
}
};
Circle c;
c.radius = 5;
cout << "圆的面积:" << c.area() << endl;
C++ 提供了三种访问控制:public、private、protected。
class Box {
private:
double width;
public:
void setWidth(double w) { width = w; }
double getWidth() { return width; }
};
class Animal {
public:
void eat() { cout << "Eating..." << endl; }
};
class Dog : public Animal {
public:
void bark() { cout << "Barking..." << endl; }
};
基类提供公共接口,派生类扩展或修改基类的行为。
class Base {
public:
virtual void show() { cout << "Base class" << endl; }
};
class Derived : public Base {
public:
void show() override { cout << "Derived class" << endl; }
};
通过基类指针调用派生类的重写方法:
Base* basePtr = new Derived();
basePtr->show();
delete basePtr;
template <typename T>
T add(T a, T b) {
return a + b;
}
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; }
};
template <>
class Pair<string> {
private:
string first, second;
public:
Pair(string a, string b) : first(a), second(b) {}
string getConcatenated() { return first + second; }
};
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;
}
异常处理用于处理运行时错误,确保程序的稳定性。
try {
throw runtime_error("发生错误");
} catch (const runtime_error& e) {
cout << "捕获到异常:" << e.what() << endl;
}
#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;
}
#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;
}
#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() {
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;
}
C++ 标准库包含了丰富的函数、类和模板,常用的 STL 组件有容器、算法和迭代器。
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;
}
namespace MyNamespace {
void display() {
cout << "Hello from MyNamespace!" << endl;
}
}
int main() {
MyNamespace::display();
return 0;
}
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;
}
#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;
}
auto 关键字、范围 for 循环、nullptr、线程库等。设计一个小型项目,定义功能模块与类结构,使用面向对象的设计原则。
使用版本控制工具(如 Git)管理代码,记录每次更新。
使用调试工具(如 GDB 或 IDE 内置调试工具)进行调试,分析性能瓶颈并进行优化。
Coursera、edX、Udacity 等平台的 C++ 课程。
参与 GitHub 上的 C++ 开源项目,学习最佳实践,提升编程能力。
加入 C++ 相关的社区与讨论组(如 Stack Overflow),向他人学习。
列出 C++ 中的所有关键字,比如 class, public, private, virtual, template 等。
sort()find()copy()transform()
微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online
通过删除不必要的空白来缩小和压缩JSON。 在线工具,JSON 压缩在线工具,online