多重继承
1、从多个基类继承
格式 :
class Sofabed : public Sofa, public Bed {
};
2、问题:二义性
两个基类有同样的成员
3、解决方法(虚拟继承)
1、可以自己强制指定 (不优雅)
s.Sofa::setWeight(100);
4、虚拟继承
1.从Sofa, Bed中取出公共特性,创建新类Furniture: 它含有weight
2.Sofa, Bed虚拟继承Furniture
3.Sofabed多重继承Sofa, Bed
格式: virtual
class Furniture {
private:
int weight;
public:
void setWeight(int weight) { this->weight = weight; }
int getWeight(void) const { return weight; }
};
class Sofa : virtual public Furniture {
private:
int a;
public:
void watchTV(void) { cout<<"watch TV"<<endl; }
};
内存情况
例子:
#include <iostream>
#include <string.h>
#include <unistd.h>
using namespace std;
class Furniture {
private:
int weight;
public:
void setWeight(int weight) { this->weight = weight; }
int getWeight(void) const { return weight; }
};
class Sofa : virtual public Furniture {
private:
int a;
public:
void watchTV(void) { cout<<"watch TV"<<endl; }
};
class Bed : virtual public Furniture {
private:
int b;
public:
void sleep(void) { cout<<"sleep"<<endl; }
};
class Sofabed : public Sofa, public Bed {
private:
int c;
};
int main(int argc, char **argv)
{
Sofabed s;
s.watchTV();
s.sleep();
s.setWeight(100);
return 0;
}