类是 C++ 面向对象的核心。构造函数负责初始化,析构函数负责释放资源。

本节要点

  • 使用 public、protected、private 控制访问。
  • 虚函数支持运行时多态。
  • RAII 利用对象生命周期管理资源。

代码示例

#include <iostream>
#include <string>

class Animal {
public:
    explicit Animal(std::string name) : name_(std::move(name)) {}
    virtual void speak() const {
        std::cout << name_ << " 发出了声音" << std::endl;
    }
    virtual ~Animal() = default;

private:
    std::string name_;
};

class Dog : public Animal {
public:
    using Animal::Animal;
    void speak() const override {
        std::cout << "汪汪" << std::endl;
    }
};

int main() {
    Dog dog("旺财");
    dog.speak();
    return 0;
}