面向对象编程

C++ 中的面向对象编程范式

object-oriented-programming.cpp

#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <algorithm>
#include <functional>

// 1. 基础类定义
class Animal {
protected:
    std::string name;
    int age;
    
public:
    // 构造函数
    Animal(const std::string& n, int a) : name(n), age(a) {
        std::cout << "Animal " << name << " created" << std::endl;
    }
    
    // 虚析构函数
    virtual ~Animal() {
        std::cout << "Animal " << name << " destroyed" << std::endl;
    }
    
    // 虚函数 - 多态的基础
    virtual void makeSound() const {
        std::cout << name << " makes a sound" << std::endl;
    }
    
    virtual void move() const {
        std::cout << name << " moves" << std::endl;
    }
    
    // 纯虚函数 - 抽象类
    virtual void eat() const = 0;
    
    // 普通成员函数
    void sleep() const {
        std::cout << name << " is sleeping" << std::endl;
    }
    
    // Getter 和 Setter
    const std::string& getName() const { return name; }
    int getAge() const { return age; }
    void setAge(int a) { age = a; }
    
    // 友元函数
    friend std::ostream& operator<<(std::ostream& os, const Animal& animal);
};

// 友元函数实现
std::ostream& operator<<(std::ostream& os, const Animal& animal) {
    os << "Animal: " << animal.name << ", Age: " << animal.age;
    return os;
}

// 2. 继承
class Dog : public Animal {
private:
    std::string breed;
    
public:
    Dog(const std::string& n, int a, const std::string& b) 
        : Animal(n, a), breed(b) {
        std::cout << "Dog " << name << " of breed " << breed << " created" << std::endl;
    }
    
    ~Dog() override {
        std::cout << "Dog " << name << " destroyed" << std::endl;
    }
    
    // 重写虚函数
    void makeSound() const override {
        std::cout << name << " barks: Woof! Woof!" << std::endl;
    }
    
    void move() const override {
        std::cout << name << " runs on four legs" << std::endl;
    }
    
    void eat() const override {
        std::cout << name << " eats dog food" << std::endl;
    }
    
    // 特有方法
    void fetch() const {
        std::cout << name << " fetches the ball" << std::endl;
    }
    
    const std::string& getBreed() const { return breed; }
};

class Cat : public Animal {
private:
    bool isIndoor;
    
public:
    Cat(const std::string& n, int a, bool indoor = true) 
        : Animal(n, a), isIndoor(indoor) {
        std::cout << "Cat " << name << " created" << std::endl;
    }
    
    ~Cat() override {
        std::cout << "Cat " << name << " destroyed" << std::endl;
    }
    
    void makeSound() const override {
        std::cout << name << " meows: Meow! Meow!" << std::endl;
    }
    
    void move() const override {
        std::cout << name << " walks silently" << std::endl;
    }
    
    void eat() const override {
        std::cout << name << " eats cat food" << std::endl;
    }
    
    // 特有方法
    void purr() const {
        std::cout << name << " purrs contentedly" << std::endl;
    }
    
    bool getIsIndoor() const { return isIndoor; }
};

// 3. 多重继承
class Flyable {
public:
    virtual void fly() const = 0;
    virtual ~Flyable() = default;
};

class Bird : public Animal, public Flyable {
private:
    double wingspan;
    
public:
    Bird(const std::string& n, int a, double ws) 
        : Animal(n, a), wingspan(ws) {
        std::cout << "Bird " << name << " with wingspan " << wingspan << " created" << std::endl;
    }
    
    ~Bird() override {
        std::cout << "Bird " << name << " destroyed" << std::endl;
    }
    
    void makeSound() const override {
        std::cout << name << " chirps: Tweet! Tweet!" << std::endl;
    }
    
    void move() const override {
        std::cout << name << " hops and flies" << std::endl;
    }
    
    void eat() const override {
        std::cout << name << " eats seeds and insects" << std::endl;
    }
    
    void fly() const override {
        std::cout << name << " flies with " << wingspan << "cm wingspan" << std::endl;
    }
    
    double getWingspan() const { return wingspan; }
};

// 4. 抽象工厂模式
class AnimalFactory {
public:
    virtual std::unique_ptr<Animal> createAnimal(const std::string& name, int age) = 0;
    virtual ~AnimalFactory() = default;
};

class DogFactory : public AnimalFactory {
public:
    std::unique_ptr<Animal> createAnimal(const std::string& name, int age) override {
        return std::make_unique<Dog>(name, age, "Mixed");
    }
};

class CatFactory : public AnimalFactory {
public:
    std::unique_ptr<Animal> createAnimal(const std::string& name, int age) override {
        return std::make_unique<Cat>(name, age, true);
    }
};

// 5. 策略模式
class FeedingStrategy {
public:
    virtual void feed(const Animal& animal) const = 0;
    virtual ~FeedingStrategy() = default;
};

class RegularFeeding : public FeedingStrategy {
public:
    void feed(const Animal& animal) const override {
        std::cout << "Feeding " << animal.getName() << " with regular food" << std::endl;
    }
};

class PremiumFeeding : public FeedingStrategy {
public:
    void feed(const Animal& animal) const override {
        std::cout << "Feeding " << animal.getName() << " with premium food" << std::endl;
    }
};

// 6. 观察者模式
class Observer {
public:
    virtual void update(const std::string& message) = 0;
    virtual ~Observer() = default;
};

class Subject {
private:
    std::vector<Observer*> observers;
    
public:
    void addObserver(Observer* observer) {
        observers.push_back(observer);
    }
    
    void removeObserver(Observer* observer) {
        observers.erase(std::remove(observers.begin(), observers.end(), observer), observers.end());
    }
    
    void notifyObservers(const std::string& message) {
        for (auto* observer : observers) {
            observer->update(message);
        }
    }
};

class ZooKeeper : public Observer {
private:
    std::string name;
    
public:
    ZooKeeper(const std::string& n) : name(n) {}
    
    void update(const std::string& message) override {
        std::cout << name << " received notification: " << message << std::endl;
    }
};

// 7. 组合模式
class Zoo : public Subject {
private:
    std::vector<std::unique_ptr<Animal>> animals;
    std::unique_ptr<FeedingStrategy> feedingStrategy;
    
public:
    Zoo(std::unique_ptr<FeedingStrategy> strategy) 
        : feedingStrategy(std::move(strategy)) {}
    
    void addAnimal(std::unique_ptr<Animal> animal) {
        animals.push_back(std::move(animal));
        notifyObservers("New animal added to zoo");
    }
    
    void feedAllAnimals() {
        for (const auto& animal : animals) {
            feedingStrategy->feed(*animal);
        }
    }
    
    void makeAllAnimalsSound() {
        for (const auto& animal : animals) {
            animal->makeSound();
        }
    }
    
    void displayAllAnimals() {
        std::cout << "\n=== Zoo Animals ===" << std::endl;
        for (const auto& animal : animals) {
            std::cout << *animal << std::endl;
        }
    }
    
    size_t getAnimalCount() const {
        return animals.size();
    }
};

// 8. 单例模式
class ZooManager {
private:
    static ZooManager* instance;
    std::string managerName;
    
    ZooManager(const std::string& name) : managerName(name) {}
    
public:
    static ZooManager* getInstance(const std::string& name = "Default Manager") {
        if (instance == nullptr) {
            instance = new ZooManager(name);
        }
        return instance;
    }
    
    void manageZoo(Zoo& zoo) {
        std::cout << managerName << " is managing the zoo with " 
                  << zoo.getAnimalCount() << " animals" << std::endl;
    }
    
    // 禁用拷贝构造和赋值
    ZooManager(const ZooManager&) = delete;
    ZooManager& operator=(const ZooManager&) = delete;
};

ZooManager* ZooManager::instance = nullptr;

// 9. 模板与面向对象结合
template<typename T>
class Container {
private:
    std::vector<T> items;
    
public:
    void add(const T& item) {
        items.push_back(item);
    }
    
    void remove(const T& item) {
        items.erase(std::remove(items.begin(), items.end(), item), items.end());
    }
    
    void forEach(std::function<void(const T&)> func) const {
        for (const auto& item : items) {
            func(item);
        }
    }
    
    size_t size() const {
        return items.size();
    }
    
    bool empty() const {
        return items.empty();
    }
};

int main() {
    std::cout << "=== C++ 面向对象编程示例 ===" << std::endl;
    
    // 1. 基础多态
    std::cout << "\n--- 多态示例 ---" << std::endl;
    std::vector<std::unique_ptr<Animal>> animals;
    animals.push_back(std::make_unique<Dog>("Buddy", 3, "Golden Retriever"));
    animals.push_back(std::make_unique<Cat>("Whiskers", 2, true));
    animals.push_back(std::make_unique<Bird>("Tweety", 1, 15.5));
    
    for (const auto& animal : animals) {
        animal->makeSound();
        animal->move();
        animal->eat();
        std::cout << std::endl;
    }
    
    // 2. 工厂模式
    std::cout << "\n--- 工厂模式 ---" << std::endl;
    DogFactory dogFactory;
    CatFactory catFactory;
    
    auto dog = dogFactory.createAnimal("Rex", 4);
    auto cat = catFactory.createAnimal("Fluffy", 3);
    
    dog->makeSound();
    cat->makeSound();
    
    // 3. 策略模式
    std::cout << "\n--- 策略模式 ---" << std::endl;
    auto regularFeeding = std::make_unique<RegularFeeding>();
    auto premiumFeeding = std::make_unique<PremiumFeeding>();
    
    Zoo zoo(std::move(regularFeeding));
    
    // 4. 观察者模式
    std::cout << "\n--- 观察者模式 ---" << std::endl;
    ZooKeeper keeper1("Alice");
    ZooKeeper keeper2("Bob");
    
    zoo.addObserver(&keeper1);
    zoo.addObserver(&keeper2);
    
    // 5. 组合模式
    std::cout << "\n--- 组合模式 ---" << std::endl;
    zoo.addAnimal(std::make_unique<Dog>("Max", 5, "Labrador"));
    zoo.addAnimal(std::make_unique<Cat>("Mittens", 3, false));
    zoo.addAnimal(std::make_unique<Bird>("Eagle", 2, 200.0));
    
    zoo.displayAllAnimals();
    zoo.feedAllAnimals();
    zoo.makeAllAnimalsSound();
    
    // 6. 单例模式
    std::cout << "\n--- 单例模式 ---" << std::endl;
    auto manager = ZooManager::getInstance("John");
    manager->manageZoo(zoo);
    
    // 7. 模板与面向对象结合
    std::cout << "\n--- 模板与面向对象结合 ---" << std::endl;
    Container<std::string> stringContainer;
    stringContainer.add("Hello");
    stringContainer.add("World");
    stringContainer.add("C++");
    
    std::cout << "String container size: " << stringContainer.size() << std::endl;
    stringContainer.forEach([](const std::string& str) {
        std::cout << "Item: " << str << std::endl;
    });
    
    // 8. 虚函数表演示
    std::cout << "\n--- 虚函数表演示 ---" << std::endl;
    Animal* animalPtr = new Dog("Virtual Dog", 2, "Mixed");
    animalPtr->makeSound();  // 调用 Dog::makeSound()
    delete animalPtr;
    
    // 9. 友元函数演示
    std::cout << "\n--- 友元函数演示 ---" << std::endl;
    Dog myDog("Friend", 4, "Poodle");
    std::cout << myDog << std::endl;
    
    // 10. 动态类型转换
    std::cout << "\n--- 动态类型转换 ---" << std::endl;
    Animal* animal = new Bird("Eagle", 3, 180.0);
    
    if (auto* bird = dynamic_cast<Bird*>(animal)) {
        bird->fly();
        std::cout << "Wingspan: " << bird->getWingspan() << "cm" << std::endl;
    }
    
    if (auto* flyable = dynamic_cast<Flyable*>(animal)) {
        flyable->fly();
    }
    
    delete animal;
    
    std::cout << "\n面向对象编程示例完成!" << std::endl;
    
    return 0;
}

Run Result

$ g++ -std=c++23 object-oriented-programming.cpp -o object-oriented-programming
$ ./object-oriented-programming
=== C++ 面向对象编程示例 ===

--- 多态示例 ---
Animal Buddy created
Dog Buddy of breed Golden Retriever created
Buddy barks: Woof! Woof!
Buddy runs on four legs
Buddy eats dog food

Animal Whiskers created
Cat Whiskers created
Whiskers meows: Meow! Meow!
Whiskers walks silently
Whiskers eats cat food

Animal Tweety created
Bird Tweety with wingspan 15.5 created
Tweety chirps: Tweet! Tweet!
Tweety hops and flies
Tweety eats seeds and insects

--- 工厂模式 ---
Animal Rex created
Dog Rex of breed Mixed created
Rex barks: Woof! Woof!
Animal Fluffy created
Cat Fluffy created
Fluffy meows: Meow! Meow!

--- 策略模式 ---
Feeding Max with regular food
Feeding Mittens with regular food
Feeding Eagle with regular food

--- 观察者模式 ---
Alice received notification: New animal added to zoo
Bob received notification: New animal added to zoo
Alice received notification: New animal added to zoo
Bob received notification: New animal added to zoo
Alice received notification: New animal added to zoo
Bob received notification: New animal added to zoo

--- 组合模式 ---
Animal Max created
Dog Max of breed Labrador created
Animal Mittens created
Cat Mittens created
Animal Eagle created
Bird Eagle with wingspan 200 created

=== Zoo Animals ===
Animal: Max, Age: 5
Animal: Mittens, Age: 3
Animal: Eagle, Age: 2
Feeding Max with regular food
Feeding Mittens with regular food
Feeding Eagle with regular food
Max barks: Woof! Woof!
Mittens meows: Meow! Meow!
Eagle chirps: Tweet! Tweet!

--- 单例模式 ---
John is managing the zoo with 3 animals

--- 模板与面向对象结合 ---
String container size: 3
Item: Hello
Item: World
Item: C++

--- 虚函数表演示 ---
Animal Virtual Dog created
Dog Virtual Dog of breed Mixed created
Virtual Dog barks: Woof! Woof!
Dog Virtual Dog destroyed
Animal Virtual Dog destroyed

--- 友元函数演示 ---
Animal: Friend, Age: 4

--- 动态类型转换 ---
Animal Eagle created
Bird Eagle with wingspan 180 created
Eagle flies with 180cm wingspan
Eagle flies with 180cm wingspan
Bird Eagle destroyed
Animal Eagle destroyed

面向对象编程示例完成!

Code Explanation

  • 封装 - 将数据和方法封装在类中,控制访问权限
  • 继承 - 子类继承父类的属性和方法
  • 多态 - 同一接口可以有不同的实现
  • 虚函数 - 支持运行时多态的关键机制
  • 抽象类 - 包含纯虚函数的类,不能实例化
  • 多重继承 - 一个类可以继承多个基类
  • 设计模式 - 解决常见问题的可重用解决方案
  • 工厂模式 - 创建对象的统一接口
  • 策略模式 - 定义算法族,使它们可以互换
  • 观察者模式 - 对象间的一对多依赖关系
  • 单例模式 - 确保类只有一个实例
  • 友元 - 允许特定函数或类访问私有成员