c++多继承
1、什么是多继承?
多继承是指一个子类继承多个父类。多继承对父类的个数没有限制,继承方式可以是公共继承、保护继承和私有继承,不写继承方式,默认是private继承。
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{ /* Sofabed继承于Sofa和Bed */
};
int main(int argc, char **argv)
{
Sofabed s;
s.watch();
s.sleep();
return 0;
}
2、多继承的二义性
参考文章:https://www.cnblogs.com/sunada2005/archive/2013/10/30/3397090.html
2.1、什么是多继承二义性
多继承有多个父类,在父类中如果出现同名,同参数,同返回值的成员,则在子类的实例化对象中调用同名的方法时则会出错,产生二义性。如下例子:在Sofa类和Bed类中都有setWeight和getWeight成员,Sofabed类继承于Sofa类和Bed类,如果在Sofabed类的实例化对象中调用setWeight或getWeight就会产生二义性,编译出错。
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, 有二义性 */
return 0;
}
2.2、怎么解决多继承二义性
方法一:类名限定
int main(int argc, char **argv)
{
Sofabed s;
s.watchTV();
s.sleep();
//s.setWeight(100); /* error, 有二义性 */
s.Sofa::setWeight(100); //使用类名限定解决多继承二义性
return 0;
}
方法二: 虚基类(用于有共同基类的场合)
虚拟继承使得类派生出的对象只继承一个基类对象。如下例子:sofabed、sofa、bed共享一个furniture基类对象
class Furniture{
private:
int weight;
public:
void setWeight(int weight)
{
this->weight = weight;
}
int getWeight(void) const
{
return weight;
}
};
class Sofa : virtual public Furniture{/* 虚拟继承Furniture类 */
private:
int a;
public:
void watchTV(void)
{
cout<<"watch TV"<<endl;
}
}
class Bed : virtual public Furniture{/* 虚拟继承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);
}