首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

关于virtual继承的有关问题

2012-04-12 
关于virtual继承的问题#includeiostreamusingnamespacestdclassSofa{public:Sofa(void){cout Watchi

关于virtual继承的问题
#include   <iostream>

using   namespace   std;


class   Sofa
{
public:
Sofa(void)
{
cout   < <   "Watching   TV.. "   < <   endl;
}

void   Setweight(int   i)
{
weight   =   i;
cout   < <   "Sofa   weight.. "   < <   endl;

}
protected:
int   weight;
};

class   Bed
{      
public:
Bed(void)
{
cout   < <   "Sleeping... "   < <   endl;
}
void   Setweight(int   i)
{
weight   =   i;
cout   < <   "Bed   weight.. "   < <   endl;
}
protected:
int   weight;
};

class   SofaBed:virtual   public   Sofa,virtual   public   Bed
{
public:
SofaBed()
{
cout   < <   "Fold   out   ... "   < <   endl;
}
};

void   main(void)
{
SofaBed   sb;
sb.Setweight(20);
}
为什么编译的时候提示F:\code\Multi-Inheritance.cpp(95)   :   error   C2385:   'SofaBed::Setweight '   is   ambiguous

而我把中间代码修改为下面的则正常呢?
/*
class   Tool
{
public:
void   Setweight(int   i)
{
weight   =   i;
cout   < <   "Sofa   weight.. "   < <   endl;
}
protected:
int   weight;
};


class   Bed:   virtual   public   Tool
{
public:
Bed(void)
{
cout   < <   "Sleeping... "   < <   endl;
}
};

class   Sofa:   virtual   public   Tool
{
  public:
Sofa(void)
{
cout   < <   "Watching   TV.. "   < <   endl;
}
};

class   SofaBed:public   Bed,public   Sofa
{
public:
SofaBed(void)
{
cout   < <   "Watching   TV   and   Sleeping... "   < <   endl;
}
};

*/


[解决办法]
啥编译器?
用devcpp和VC2005express都编译一下看看结果。
一个编译器不说明问题。
[解决办法]
第一个为什么错误:
你要指定用soft还是bed的Setweight方法,你再main中直接用派生类的Setweight方法,对派生类来说它不知道你要用的哪个类的方法,所以出错。应该类似于下面的这种写法
void main(void)
{
SofaBed sb;
(soft)sb.Setweight(20);
//sb.Setweight(20);
}

第二个为什么正确:
soft和bed的Setweight方法都是基类Tool的方法,所以就指定了Setweight是Tool的,而不是soft或者bed,如果soft和bed重写了基类Tool的Setweight方法,你的第二个也会出错的。


[解决办法]
虚拟继承不是这么用的啊

SofaBed应该产生两个父类的父类的方法的一个实例
所以还应该构建一个类,Sofa和Bed都继承自这个类,并且这个类要包含Setweight方法
[解决办法]
void main(void)
{
SofaBed sb;
sb.Sofa::Setweight(20);
or-> sb.Bed::Setweight(20);

}
[解决办法]
sb.Sofa::Setweight(20);// sb.Bed::Setweight(20);


[解决办法]
这个就是virtual继承的含义阿

没virtual virtual继承时:
A A A
\ / / \
B C B C
\ / \ /
D D

热点排行