610's Algorithm Teaching

面向对象编程

面向对象编程概述

面向对象编程(OOP)是一种编程范式,它使用"对象"来设计软件。OOP的主要特征包括封装、继承和多态。C++是一门支持面向对象编程的语言。

类与对象

类是对象的模板,定义了对象的属性和方法。对象是类的实例化。

// 类的定义
class Person {
private:
    string name;
    int age;

public:
    Person(string n, int a) {
        name = n;
        age = a;
    }

    void introduce() {
        std::cout << "我叫" << name << ",今年" << age << "岁。" << std::endl;
    }

    void setAge(int a) {
        age = a;
    }

    int getAge() {
        return age;
    }
};

// 对象的创建和使用
Person person1("张三", 25);
person1.introduce();
person1.setAge(26);
std::cout << "年龄:" << person1.getAge() << std::endl;

封装

封装是将数据和操作数据的方法捆绑在一起,并隐藏内部实现细节。C++通过访问修饰符实现封装。

class BankAccount {
private:
    double balance;

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

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

    bool withdraw(double amount) {
        if (amount > 0 && balance >= amount) {
            balance -= amount;
            return true;
        }
        return false;
    }

    double getBalance() {
        return balance;
    }
};

继承

继承允许创建新类(派生类)从现有类(基类)继承属性和方法,实现代码重用。

// 基类
class Animal {
public:
    void eat() {
        std::cout << "动物吃东西" << std::endl;
    }

    virtual void makeSound() {
        std::cout << "动物发出声音" << std::endl;
    }
};

// 派生类
class Dog : public Animal {
public:
    void makeSound() override {
        std::cout << "汪汪汪" << std::endl;
    }

    void fetch() {
        std::cout << "狗捡球" << std::endl;
    }
};

// 派生类
class Cat : public Animal {
public:
    void makeSound() override {
        std::cout << "喵喵喵" << std::endl;
    }

    void climb() {
        std::cout << "猫爬树" << std::endl;
    }
};

多态

多态允许不同类的对象对同一消息做出不同的响应。C++通过虚函数和函数重载实现多态。

// 多态示例
void animalSound(Animal* animal) {
    animal->makeSound();
}

int main() {
    Dog dog;
    Cat cat;

    animalSound(&dog); // 输出:汪汪汪
    animalSound(&cat); // 输出:喵喵喵

    return 0;
}

构造函数与析构函数

构造函数在对象创建时自动调用,用于初始化对象。析构函数在对象销毁时自动调用,用于清理资源。

class Student {
private:
    string name;
    int* scores;
    int numScores;

public:
    Student(string n, int num) {
        name = n;
        numScores = num;
        scores = new int[num];
        std::cout << "构造函数被调用" << std::endl;
    }

    ~Student() {
        delete[] scores;
        std::cout << "析构函数被调用" << std::endl;
    }
};

运算符重载

运算符重载允许为自定义类型定义运算符的行为。

class Complex {
private:
    double real;
    double imag;

public:
    Complex(double r, double i) : real(r), imag(i) {}

    Complex operator+(const Complex& other) {
        return Complex(real + other.real, imag + other.imag);
    }

    void print() {
        std::cout << real << " + " << imag << "i" << std::endl;
    }
};

学习建议

  • 理解面向对象编程的核心概念:封装、继承、多态
  • 合理使用访问修饰符实现封装
  • 通过继承实现代码重用和扩展
  • 使用虚函数实现运行时多态
  • 注意构造函数和析构函数的正确使用
  • 理解运算符重载的使用场景
返回C++教程