深入理解C++多重继承机制
1. 描述多重继承机制
在C++中,多重继承是指一个派生类可以从多个基类继承属性和行为。这种特性允许我们创建更加灵活和强大的类结构,但也引入了一些复杂性。为了更好地理解多重继承,让我们从一个具体的例子出发:沙发床(Sleeper Sofa)。
沙发床是一种既可以作为沙发又可以作为床使用的家具。在C++中,我们可以设计一个类 SleeperSofa ,它同时继承自 Sofa 和 Bed 两个基类。这样, SleeperSofa 就可以获得这两个类的所有功能。
class Bed {
public:
Bed() {}
void sleep() { cout << "Sleep" << endl; }
int weight;
};
class Sofa {
public:
Sofa() {}
void watchTV() { cout << "Watch TV" << endl; }
int weight;
};
class SleeperSofa : public Bed, public Sofa {
public:
SleeperSofa() {}
void foldOut() { cout << "Fold out" << endl; }
};
在这个例子中, SleeperSofa
超级会员免费看
订阅专栏 解锁全文
1022

被折叠的 条评论
为什么被折叠?



