C++中类的多继承

C++中类的多继承在写这一主题的文章之前 在网上找到一篇很非常好的文章 C 之继承与多态 就没有必要做重复造轮子的事件了 那就从这篇文章开始吧 在 c 中一个类可以从多个基类中派生 即可以有多个父类 这就是多继承 多继承的方式主要有两种 1 简单版本类 C 会同时拥有类 A 和类 B 的特性 属性和方法 也就是两个类的所有成员 这种方式很简单这里就不多说 主要讲下面这种方式 2 复杂版本同样的 这个结构中

在写这一主题的文章之前,在网上找到一篇很非常好的文章C++之继承与多态。就没有必要做重复造轮子的事件了,那就从这篇文章开始吧!

在c++中一个类可以从多个基类中派生(即可以有多个父类),这就是多继承。多继承的方式主要有两种:

1. 简单版本


这里写图片描述






类C会同时拥有类A和类B的特性(属性和方法,也就是两个类的所有成员)。这种方式很简单这里就不多说,主要讲下面这种方式。


2. 复杂版本



这里写图片描述






同样的,这个结构中类C也会同时拥有类A和类B的特性,但这就会有一个问题,类B1和B2都继承自A,那么类C的对象会同时包含两个A的对象。这样就会带来很多歧义性。


这里写图片描述
类的关系图



代码:

#pragma once #include 
      #include 
      using namespace std; class Furniture { public: Furniture(void) : m_weight(0){} Furniture(double weight) : m_weight(weight){} ~Furniture(void){} double GetWeight() const { return m_weight; } void SetWeight(double val) { m_weight = val; } private: double m_weight; }; class Bed : public Furniture { public: Bed() : Furniture(), m_second(0) {} Bed(double weight, int second) : Furniture(weight), m_second(second){} void Sleep(int second) { m_second = second; cout << "休息" << m_second << "秒..."<< endl; } private: int m_second; }; class Sofa : public Furniture { public: Sofa() : Furniture() {} Sofa(double weight) : Furniture(weight){} void WatchTV(string programme) { cout << "正在看" << programme << "节目..." << endl; } }; class SleepSofa : public Bed, public Sofa { public: SleepSofa() : Bed(), Sofa() {} SleepSofa(double weight, int second) : Bed(weight, second), Sofa(weight) {} void FoldOut() { cout << "展开沙发当床用." << endl; Sleep(360); } };

SleepSofa类继承自Bed和Sofa两个类,因此,SleepSofa类拥有这两个类的特性,但在实际编码中会存在如下几个问题。

1.SleepSofa类该如何定义?

Class SleepSofa : public Bed, public Sofa { … } 

构造顺序为:Bed sofa sleepsofa (也就是书写的顺序)

2.Bed和Sofa类都继承自Furniture,都有Weight属性也都有GetWeight和SetWeight方法,在SleepSofa类中使用这些属性和方法时,如何确定调用的是哪个类的成员?

我们看一下测试样例:

void Test() { SleepSofa sleepSofa; sleepSofa.SetWeight(55); double weight = sleepSofa.GetWeight(); }

这时会有以下错误:

就是说SetWeight和GetWeight是有歧义的。

SleepSofa sleepSofa; sleepSofa.Bed::SetWeight(55); sleepSofa.Sofa::SetWeight(80); 


这里写图片描述

class Furniture{……}; class Bed : virtual public Furniture{……}; // 这里我们使用虚继承 class Sofa : virtual public Furniture{……};// 这里我们使用虚继承 class SleepSofa : public Bed, public Sofa {……}; 
SleepSofa sleepSofa; sleepSofa.SetWeight(80); 


这里写图片描述


这里写图片描述



总结

  1. 在程序设计中最好不要出现多继承,要有也是继承多个作为接口使用抽象类(只声明需要的功能,没有具体的实现)。因为出现一般的多继承本身就是一种不好的面向对象程序设计。
  2. 在出现版本2的多继承时使用虚继承的方式。







版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/217859.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月18日 上午8:36
下一篇 2026年3月18日 上午8:36


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号