C++——类的继承

类的继承

继承是一个新类(派生类)基于现有类(基类),实现代码复用和扩展。

cpp 复制代码
// 基类
class Animal {
public:
    string name;
    Animal(string n) : name(n) {}
    void eat() { cout << name << " is eating." << endl; }
};

// 派生类
class Bird : public Animal {
public:
    int wingspan;
    Bird(string n, int w) : Animal(n), wingspan(w) {}
    void fly() { cout << name << " is flying." << endl; }
};

int main() {
    Bird sparrow("Sparrow", 20);
    sparrow.eat();  // 调用基类的成员函数
    sparrow.fly();  // 调用派生类的成员函数
    return 0;
}

要点:

  • 子类继承父类,拥有父类所有非私有成员。
  • 父类的私有成员在子类中无法访问,但受保护的成员可以访问。
  • 函数重写:子类可以定义与父类同名函数,实现功能的覆盖。

protected 访问权限

  • 继承方式:
    • 公有继承 (public):父类成员的访问权限在子类中保持不变。
    • 私有继承 (private):父类所有成员在子类中都变成私有权限。

public 关键字用于定义共有的成员,这些成员能在任何地方访问,不局限于内部。(江山) protected 关键字用于定义受保护的成员,这些成员只能在类内部和派生类中访问。(玉玺) private 关键字用于定义私有成员,这些成员只能在类内部访问。(皇后)

cpp 复制代码
class Animal {
protected:
    int age;
};

class Dog : public Animal {
public:
    void setAge(int a) { age = a; } // 可以访问 protected 成员
};

int main() {
    Dog myDog;
    // myDog.age = 5;  // 错误,无法直接访问 protected 成员
    myDog.setAge(5); 
    return 0;
}

final 阻止继承

final 关键字可以用于阻止类被继承,或者阻止虚函数被重写。

cpp 复制代码
class Shape {
public:
    virtual void draw() = 0;
};

class Circle : public Shape {
public:
    void draw() final { /* 实现 */ }  // final 阻止该函数被重写
};

//class SubCircle : public Circle { ... };  // 错误,Circle 类被 final 修饰,无法被继承

要点:

  • 使用 final 修饰的类无法被继承。
  • 使用 final 修饰的虚函数无法被重写。

相关推荐
一灯架构3 小时前
90%的人答错!一文带你彻底搞懂ArrayList
java·后端
mldong4 小时前
Python开发者狂喜!200+课时FastAPI全栈实战合集,10大模块持续更新中🔥
后端
GreenTea5 小时前
从 Claw-Code 看 AI 驱动的大型项目开发:2 人 + 10 个自治 Agent 如何产出 48K 行 Rust 代码
前端·人工智能·后端
Moment7 小时前
AI 全栈指南:NestJs 中的 Service Provider 和 Module
前端·后端·面试
IT_陈寒7 小时前
为什么我的JavaScript异步回调总是乱序执行?
前端·人工智能·后端
Moment7 小时前
AI全栈入门指南:NestJs 中的 DTO 和数据校验
前端·后端·面试
小村儿8 小时前
Harness Engineering:为什么你用 AI 越用越累?
前端·后端·ai编程
小码哥_常8 小时前
为什么PUT和DELETE请求在大公司中逐渐被弃用?
后端
宫_商_角_徵8 小时前
动态代理到底在做什么?
后端
苍何8 小时前
我把微信 cli 开源了,群消息终于不用爬楼了!
后端