继承(四)

来源:互联网 发布:自动变速箱测试软件 编辑:程序博客网 时间:2024/06/05 06:19

1.多重继承

   (1)单一继承--一个派生类最多只能有一个基类

   (2)多重继承----一个派生类可以有多个基类

            [1]class 类名 : 继承方式 基类1, 继承方式 基类2,... { };

    [2]派生类同时继承多个基类的成员,更好的软件重用

            [3]可能会有大量的二义性,多个基类中可能包含同名变量或函数

    (3)多重继承中解决访问歧义的方法:基类名::数据成员名(或成员函数(参数表))

            [1]明确指明要访问定义于哪个类中的成员


#include <iostream>using namespace std;class Furniture {public:Furniture(int weight) : weight_(weight) {}public:int weight_;};class Bed : public Furniture { public:Bed(int weight) : Furniture(weight) {}void Sleep() {cout << "Sleep ..." << endl;}};class Sofa : public Furniture {public:Sofa(int weight) : Furniture(weight) {}void WatchTV() {cout << "Watch TV ..." << endl;}};class SofaBed : public Bed, public Sofa {public:SofaBed(int weight) : Sofa(weight), Bed(weight)  {FoldIn();}void FoldOut() {cout << "FoldOut ..." << endl;}void FoldIn() {cout << "FoldIn ..." << endl;}};int main(void) {SofaBed sb(10);//sb.weight_ = 200;sb.Sofa::weight_ = 300;sb.Bed::wieght_ = 400;sb.WatchTV();sb.FoldOut();sb.Sleep();return 0;}

2.虚基类与虚继承

   (1)当派生类从多个基类派生,而这些基类又从同一个基类派生,则在访问此共同基类的成员时,将产生二义性----采用虚基类来解决。

   (2)虚基类的引入:用于有共同基类的场合(钻石)

   (3)声明:以virtual修饰说明基类。例:class B1:virtual public BB

   (4)作用:

              [1]主要用来解决多继承是可能发生的对同一基类继承多次而产生的二义性问题。

              [2]为最远的派生类提供唯一的基类成员,而不重复产生多次拷贝


#include <iostream>using namespace std;class Furniture {public:/*Furniture() {}*/Furniture(int weight) : weight_(weight) {cout << "Furniture ..." << endl;}~Furniture() {cout << "~Furniture ..." << endl;}public:int weight_;};class Bed : virtual public Furniture { public:Bed(int weight) : Furniture(weight) {cout << "Bed ..." << endl;}~Bed() {cout << "~Bed ..." << endl;}void Sleep() {cout << "Sleep ..." << endl;}};class Sofa : virtual public Furniture {public:Sofa(int weight) : Furniture(weight) {cout << "Sofa ..." << endl;}~Sofa() {cout << "~Sofa ..." << endl;}void WatchTV() {cout << "Watch TV ..." << endl;}};class SofaBed : public Bed, public Sofa {public:SofaBed(int weight) : Sofa(weight), Bed(weight), Furniture(weight)  {cout  << "SofaBed ..." << endl;FoldIn();}~SofaBed() {cout  << "~SofaBed ..." << endl;}void FoldOut() {cout << "FoldOut ..." << endl;}void FoldIn() {cout << "FoldIn ..." << endl;}};int main(void) {SofaBed sb(10);sb.weight_ = 200;sb.FoldOut();sb.WatchTV();sb.Sleep();return 0;}

3.虚基类及派生类构造函数

   (1)虚基类的成员是由最远派生类的构造函数通过调用虚基类的构造函数进行初始化的。

   (2)在整个继承结构中,直接或间接继承虚基类的所有派生类,都必须在构造函数的成员初始化列表中给出对虚基类的构造函数调用。如果未列出,则表示调用该虚基类的默认构造函数。

   (3)在建立对象时,只有最派生类的构造函数调用虚基类的构造函数,该派生类的其他类对虚基类构造函数的调用被忽略。

原创粉丝点击