类的继承
继承是一个新类(派生类)基于现有类(基类),实现代码复用和扩展。
// 基类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 关键字用于定义私有成员,这些成员只能在类内部访问。(皇后)
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 关键字可以用于阻止类被继承,或者阻止虚函数被重写。
class Shape {public: virtual void draw() = 0;};class Circle : public Shape {public: void draw() final { /* 实现 */ } // final 阻止该函数被重写};//class SubCircle : public Circle { ... }; // 错误,Circle 类被 final 修饰,无法被继承要点:
- 使用
final 修饰的类无法被继承。使用 final 修饰的虚函数无法被重写。