关于多重继承
#include"iostream.h"
class bed
{
public:
bed():weight(0){}
void sleep()
{
cout<<"sleep\n";
}
void setweight(int i)
{
weight=i;
}
protected:
int weight;
};
class sofa
{
public:
sofa():weight(0){}
void watchtv()
{
cout<<"watch tv\n";
}
void setweight(int i){weight=i;}
protected:
int weight;
};
class sleepersofa:public bed,public sofa
{
public:
sleepersofa(){}
void foldout()
{
cout<<"fold out\n";
}
};
int main()
{
sleepersofa ss;
ss.sofa.setweight(20);
return 0;
}
error c2274: function-style cast : illegal as right side of . operator
error c2228: left of .setweight must have class/struct/union type
error executing cl.exe.
多重继承.obj - 2 error(s), 0 warning(s)
//我用的是vc 6.0
//错在哪里
推荐阅读
ss.sofa.setweight(20);
错误!
应该这样调用函数
ss.sofa::setweight(20);
明确地告诉编译器调用哪个父类的函数,不然编译器不知道调用哪个。
这一句ss.sofa.setweight(20);改为ss.sofa::setweight(20);
sleepersofa继承了sofa之后,因为有了同名的setweight,所以出现二义性。用ss.setweight(20)表示要调用sleepersofa的实现,用ss.sofa::setweight(20)表示要用sofa的实现。


讨论区