面向对象编程(OOP)是C++编程语言的核心特性之一。它允许开发者创建可重用、可维护和易于理解的代码。以下是一些关于C++面向对象编程的基础知识。

类和对象

在OOP中,类是创建对象的蓝图。对象是类的实例。

  • :定义了对象的属性(数据)和方法(行为)。
  • 对象:类的具体实例,具有类的属性和方法。
class Car {
public:
    std::string brand;
    int year;

    void startEngine() {
        // 启动引擎的逻辑
    }
};

Car myCar;
myCar.brand = "Toyota";
myCar.year = 2020;
myCar.startEngine();

继承

继承允许一个类继承另一个类的属性和方法。

class SportsCar : public Car {
public:
    void accelerate() {
        // 加速的逻辑
    }
};

多态

多态允许不同的对象对同一消息做出响应。

class Animal {
public:
    virtual void makeSound() {
        // 做出声音的逻辑
    }
};

class Dog : public Animal {
public:
    void makeSound() override {
        std::cout << "Woof!" << std::endl;
    }
};

class Cat : public Animal {
public:
    void makeSound() override {
        std::cout << "Meow!" << std::endl;
    }
};

封装

封装是隐藏对象的内部状态和实现细节,仅通过公共接口与外界交互。

class BankAccount {
private:
    double balance;

public:
    BankAccount(double initialBalance) : balance(initialBalance) {}

    double getBalance() const {
        return balance;
    }

    void deposit(double amount) {
        balance += amount;
    }

    void withdraw(double amount) {
        if (amount <= balance) {
            balance -= amount;
        }
    }
};

更多资源

想要了解更多关于C++面向对象编程的知识,请访问我们的面向对象编程指南

C++ Class Diagram