1.多重继承
#include <iostream>
#include <string.h>
#include <unistd.h>
using namespace std;
class Sofa {
public:
void watchTV(void) { cout<<"watch TV"<<endl; }
};
class Bed {
public:
void sleep(void) { cout<<"sleep"<<endl; }
};
class Sofabed : public Sofa, public Bed {
};
int main(int argc, char **argv)
{
Sofabed s;
s.watchTV();
s.sleep();
return 0;
}
#include <iostream>
#include <string.h>
#include <unistd.h>
using namespace std;
class Sofa {
private:
int weight;
public:
void watchTV(void) { cout<<"watch TV"<<endl; }
void setWeight(int weight) { this->weight = weight; }
int getWeight(void) const { return weight; }
};
class Bed {
private:
int weight;
public:
void sleep(void) { cout<<"sleep"<<endl; }
void setWeight(int weight) { this->weight = weight; }
int getWeight(void) const { return weight; }
};
class Sofabed : public Sofa, public Bed {
};
int main(int argc, char **argv)
{
Sofabed s;
s.watchTV();
s.sleep();
//s.setWeight(100); /* error, 有二义性 */
s.Sofa::setWeight(100);
return 0;
}
2.虚拟继承
.................................................................................
#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;
}
3.总结
a.一个派生类可以有多个基类
b.可能有二义性,解决办法:虚拟继承,Softbed的基类Soft、Bed共享一个Furniture对象
尽量避免使用多重继承,它使得程序变得十分复杂