第15章 - 封装、继承、多态
嗨,朋友!我是长安。
这一章我们要学习面向对象编程的三大特性:封装、继承、多态。这是C++最核心的内容!
🔒 封装(Encapsulation)
封装就是把数据和操作数据的方法绑定在一起,隐藏内部实现细节。
class BankAccount {
private:
double balance; // 隐藏数据
public:
void deposit(double amount) { // 提供接口
if (amount > 0) {
balance += amount;
}
}
double getBalance() {
return balance;
}
};
🧬 继承(Inheritance)
继承允许创建新类(子类)来扩展现有类(父类)的功能。
// 基类(父类)
class Animal {
protected:
string name;
public:
Animal(string n) : name(n) {}
void eat() {
cout << name << " 正在吃东西" << endl;
}
};
// 派生类(子类)
class Dog : public Animal {
public:
Dog(string n) : Animal(n) {}
void bark() {
cout << name << " 汪汪叫!" << endl;
}
};
int main() {
Dog dog("旺财");
dog.eat(); // 继承自Animal
dog.bark(); // Dog自己的方法
}
🎭 多态(Polymorphism)
多态允许使用父类指针调用子类的方法。需要使用virtual关键字。
class Shape {
public:
virtual double getArea() { // 虚函数
return 0;
}
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double getArea() override {
return 3.14 * radius * radius;
}
};
class Rectangle : public Shape {
private:
double width, height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
double getArea() override {
return width * height;
}
};
int main() {
Shape* shapes[2];
shapes[0] = new Circle(5);
shapes[1] = new Rectangle(4, 6);
for (int i = 0; i < 2; i++) {
cout << "面积:" << shapes[i]->getArea() << endl; // 多态调用
}
}
🎯 小结
- 封装:隐藏细节,提供接口
- 继承:代码复用,扩展功能
- 多态:同一接口,不同实现
➡️ 第16章 - 运算符重载
