C++ 核心编程

C++ 是一种强大且复杂的编程语言,结合了 低级系统编程 和 高级抽象 的特性。了解 C++ 的核心概念是高效编程的基础。以下是 C++ 核心编程的几个重要概念,涵盖了从基础到高级的常见特性。


1. C++ 基础语法

1.1 变量与数据类型

C++ 支持多种数据类型,常见的包括:

int a = 10;       // 整数类型
float f = 3.14;   // 浮点数类型
double d = 3.141592; // 双精度浮点类型
char c = 'A';     // 字符类型
bool b = true;    // 布尔类型

  • int:整型,用于表示整数。
  • float:单精度浮点型。
  • double:双精度浮点型。
  • char:字符型,通常用于存储一个字符。
  • bool:布尔型,存储 true 或 false

1.2 控制结构

C++ 支持标准的控制结构,如 ifforwhile 等。

// 条件语句
if (a > b) {
    cout << "a is greater than b" << endl;
} else {
    cout << "b is greater than or equal to a" << endl;
}

// 循环语句
for (int i = 0; i < 5; ++i) {
    cout << i << " ";
}
cout << endl;

// while 循环
int i = 0;
while (i < 5) {
    cout << i << " ";
    ++i;
}
cout << endl;


2. 面向对象编程 (OOP)

C++ 支持面向对象编程,通过类和对象的概念来组织代码。

2.1 类与对象

类是数据和函数的封装体,用于创建对象。

class Car {
public:
    // 数据成员
    string brand;
    int year;

    // 构造函数
    Car(string b, int y) : brand(b), year(y) {}

    // 成员函数
    void display() {
        cout << "Brand: " << brand << ", Year: " << year << endl;
    }
};

int main() {
    Car car1("Toyota", 2020);  // 创建对象
    car1.display();            // 调用成员函数
    return 0;
}

2.2 继承

C++ 支持通过继承创建新类,使得一个类可以继承另一个类的属性和方法。

class Vehicle {
public:
    string brand;
    Vehicle(string b) : brand(b) {}
    void display() {
        cout << "Brand: " << brand << endl;
    }
};

class Car : public Vehicle {
public:
    int year;
    Car(string b, int y) : Vehicle(b), year(y) {}
    void display() {
        Vehicle::display(); // 调用基类的 display
        cout << "Year: " << year << endl;
    }
};

int main() {
    Car car("Toyota", 2021);
    car.display();
    return 0;
}

2.3 多态

C++ 支持多态,通过虚函数和继承实现。

class Animal {
public:
    virtual void sound() { cout << "Animal sound" << endl; }  // 虚函数
};

class Dog : public Animal {
public:
    void sound() override { cout << "Bark" << endl; }  // 重写基类方法
};

int main() {
    Animal* animal = new Dog();  // 父类指针指向子类对象
    animal->sound();             // 输出 "Bark"
    delete animal;
    return 0;
}


3. C++ 高级特性

3.1 模板 (Templates)

模板是 C++ 强大的泛型编程特性,可以让你编写通用的代码,适用于不同的数据类型。

template <typename T>
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;
}

3.2 智能指针

C++11 引入了智能指针,主要包括 std::unique_ptrstd::shared_ptr 和 std::weak_ptr,用于自动管理动态分配的内存。

#include <memory>

int main() {
    // unique_ptr 不允许拷贝,但可以转移所有权
    std::unique_ptr<int> p1 = std::make_unique<int>(10);
    cout << *p1 << endl;

    // shared_ptr 可以共享所有权
    std::shared_ptr<int> p2 = std::make_shared<int>(20);
    cout << *p2 << endl;
    return 0;
}

3.3 Lambda 表达式

Lambda 表达式允许你创建匿名函数,可以在需要函数作为参数时使用。

#include <algorithm>
#include <vector>

int main() {
    vector<int> vec = {1, 2, 3, 4, 5};

    // 使用 lambda 表达式打印每个元素
    for_each(vec.begin(), vec.end(), [](int i) { cout << i << " "; });
    cout << endl;

    return 0;
}

3.4 STL(标准模板库)

C++ 提供了标准模板库(STL),其中包括常用的数据结构和算法,如向量(std::vector)、列表(std::list)、集合(std::set)等。

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> vec = {5, 2, 8, 1, 3};
    
    // 排序
    std::sort(vec.begin(), vec.end());
    
    // 打印排序后的结果
    for (int num : vec) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    
    return 0;
}


4. 异常处理

C++ 支持异常处理机制,通过 trycatch 和 throw 来捕获和抛出异常。

#include <iostream>
using namespace std;

int divide(int a, int b) {
    if (b == 0) {
        throw runtime_error("Division by zero");
    }
    return a / b;
}

int main() {
    try {
        cout << divide(10, 2) << endl;  // 正常
        cout << divide(10, 0) << endl;  // 会抛出异常
    } catch (const exception& e) {
        cout << "Error: " << e.what() << endl;
    }
    return 0;
}


5. C++ 内存管理

C++ 提供了低级的内存管理功能,开发者需要手动管理内存的分配和释放。

5.1 new 与 delete

int* ptr = new int(10);   // 动态分配内存
cout << *ptr << endl;     // 输出 10
delete ptr;               // 释放内存

5.2 new[] 与 delete[]

int* arr = new int[5];    // 动态分配数组
arr[0] = 10;              // 数组赋值
delete[] arr;             // 释放数组内存


6. C++ 编译与调试

  • 编译 C++ 程序
    使用 g++ 编译器来编译 C++ 代码:g++ -o my_program my_program.cpp # 编译源代码为可执行文件 ./my_program # 运行程序
  • 调试 C++ 程序
    使用 gdb 调试器来调试 C++ 程序:g++ -g -o my_program my_program.cpp # 使用 -g 选项生成调试信息 gdb ./my_program # 启动调试器

总结

C++ 是一种功能强大的编程语言,它结合了低级操作的灵活性和高级抽象的便捷性。通过掌握 C++ 的基本语法、面向对象编程、模板编程、异常处理以及内存管理,你可以高效地编写复杂的应用程序。在 C++ 的学习过程中,理解其核心概念,如类与对象、继承与多态、STL 和内存管理,对于深入掌握 C++ 编程至关重要。