关于virtual继承的问题

gwenxia 2007-07-16 04:41:08
#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;
}
};

*/
...全文
201 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
yinenlai 2007-07-17
  • 打赏
  • 举报
回复
这个就是virtual继承的含义阿

没virtual virtual继承时:
A A A
\ / / \
B C B C
\ / \ /
D D
bombwang 2007-07-16
  • 打赏
  • 举报
回复
sb.Sofa::Setweight(20);// sb.Bed::Setweight(20);
ReachZh 2007-07-16
  • 打赏
  • 举报
回复
void main(void)
{
SofaBed sb;
sb.Sofa::Setweight(20);
or-> sb.Bed::Setweight(20);

}
dx30611 2007-07-16
  • 打赏
  • 举报
回复
虚拟继承不是这么用的啊

SofaBed应该产生两个父类的父类的方法的一个实例
所以还应该构建一个类,Sofa和Bed都继承自这个类,并且这个类要包含Setweight方法
ReachZh 2007-07-16
  • 打赏
  • 举报
回复
第一个为什么错误:
你要指定用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方法,你的第二个也会出错的。

taodm 2007-07-16
  • 打赏
  • 举报
回复
啥编译器?
用devcpp和VC2005express都编译一下看看结果。
一个编译器不说明问题。

64,690

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧