C++ 继承和多态

定义:

继承是一种面向对象编程的重要特性,它允许你创建一个新的类,从一个或多个现有的类中继承属性的行为。
这个新的类被称为 派生类(Derived Class),而被继承的类称之为基类(Base Class)。

继承所研究的是类与类之间的依赖关系,是多个类直接的共性与个性直接的代码表达。让代码结构更加合理,灵活,易于维护。

继承

单继承

C++ 继承和多态_第1张图片

class BaseClass {};
class Derive : public BaseClass { };
多继承

C++ 继承和多态_第2张图片

#include 
using namespace std;

// 基类 Animal
class Animal {
public:
    void eat() {
        cout << "This animal is eating." << endl;
    }
    void sleep() {
        cout << "This animal is sleeping." << endl;
    }
};

// 基类 Bird
class Bird {
public:
    void fly() {
        cout << "This bird is flying." << endl;
    }
    void nest() {
        cout << "This bird is building a nest." << endl;
    }
};

// 基类 Bird
class Bird {
public:
    void fly() {
        cout << "This bird is flying." << endl;
    }
    void nest() {
        cout << "This bird is building a nest." << endl;
    }
};

// 基类 Predator
class Predator{
public:
    void hunt() {
        cout << "This bird is hunt." << endl;
    }
};

// 派生类 Eagle
class Eagle : public Animal, public Bird, public Predator{
public:
    void hunt() {
        cout << "This eagle is hunting." << endl;
    }
};

int main() {
    Eagle eagle;
    eagle.eat();    // 从 Animal 类继承
    eagle.fly();    // 从 Bird 类继承
    eagle.hunt();   // Eagle 类自己的方法
    return 0;
}

菱形继承

C++ 继承和多态_第3张图片


class Animal {};
class Horse :public Animal {};
class Donkey :public Animal {};
class Mule :public Horse,public Donkey {};

在实际的业务设计时,往往将共性的东西 设计为基类,将个性化的东西,设计在派生类里。

多态

静态多态

  • 函数重载
  • 运算符重载

动态多态

  • 虚函数
  • 继承对象之间的指针 & 引用

练一练:

如何实现一个不可以被继承的类

1.使用 C++ 11 final 关键字

class A final{};
这个类将不能被继承

2.使用 privete 或 protected 构造函数来防止继承

将类的构造函数声明为 private 或 protected 来避免该类被继承。这样可以防止外部代码直接创建该类的派生类实例

class NonInheritable {
private:
    // 将构造函数设为私有,禁止派生类调用
    NonInheritable() {}

public:
    void showMessage() {
        cout << "This class cannot be inherited due to private constructor." << endl;
    }

    static NonInheritable create() {
        return NonInheritable();  // 提供静态方法创建对象
    }
};

// 尝试继承会报错,因为构造函数是私有的
class Derived : public NonInheritable {
public:
    void anotherMessage() {
        cout << "This will not compile." << endl;
    }
};

调用 Derived 将会报错:
E1790	无法引用 "Derived" 的默认构造函数

你可能感兴趣的:(基础,c++,开发语言)