问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

C++ 继承和多态详解

创作时间:
2025-03-11 12:34:31
作者:
@小白创作中心

C++ 继承和多态详解

引用
CSDN
1.
https://m.blog.csdn.net/Tiantangbujimo7/article/details/145320530

C++中的继承和多态是面向对象编程的重要特性,它们允许开发者创建结构合理、灵活且易于维护的代码。本文将详细介绍继承的类型、多态的概念以及如何实现不可继承的类。

继承

继承是一种面向对象编程的重要特性,它允许你创建一个新的类,从一个或多个现有的类中继承属性的行为。这个新的类被称为派生类(Derived Class),而被继承的类称之为基类(Base Class)。继承所研究的是类与类之间的依赖关系,是多个类直接的共性与个性直接的代码表达。让代码结构更加合理,灵活,易于维护。

单继承

单继承是最基本的继承方式,一个派生类只能继承一个基类。

class BaseClass {};
class Derive : public BaseClass { };

多继承

多继承允许一个派生类继承多个基类。但是,多继承可能会导致一些复杂的问题,如菱形继承问题。

#include <iostream>
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;
    }
};

// 基类 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;
}

菱形继承

菱形继承是一种特殊的多继承情况,可能会导致一些复杂的问题。

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

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

多态

多态是面向对象编程的另一个重要特性,它允许使用一个接口来表示多种类型。多态可以分为静态多态和动态多态。

静态多态

静态多态在编译时就确定,主要包括函数重载和运算符重载。

动态多态

动态多态在运行时确定,主要包括虚函数和继承对象之间的指针与引用。

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

有时候,我们可能希望创建一个不能被继承的类。以下是两种实现方法:

  1. 使用 C++11 的 final 关键字
class A final{};

这个类将不能被继承。

  1. 使用 private 或 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" 的默认构造函数
© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号