关于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;
}
};
*/
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;
}
};
*/
...全文
相关推荐
cpp代码-C++:类04__虚继承 virtual 避免菱形继承的问题
cpp代码-C++:类04__虚继承 virtual 避免菱形继承的问题
关于C++中菱形继承和虚继承的问题总结
C++的三大特性为:封装,继承,多态。但是在继承中,存在一些使用方面的问题需要注意,下面这篇文章主要给大家总结介绍了关于C++中菱形继承和虚继承的问题,需要的朋友可以参考借鉴,下面来一起看看吧。
C++中virtual继承的深入理解
今天专门看了一下虚继承的东西,以前都没怎么用过,具体如下:父类: 代码如下:class CParent { …. }; 继承类的声明比较特别: class CChild : virtual public CParent { …. } 请问,这个”virtual”是什么作用及含义? ————————————————————— 表示虚拟继承,和普通继承是C++的两种继承方式。 例如B1、B2 继承A 而C多重继承B1、B2 如果普通继承则C包含两份A的拷贝,分别来自于B1、B2 而虚拟继承则只包含一份A的拷贝 ————————————————————— 这个”
virtual_base_class.rar_virtual base cla_virtual base class
虚基类是面向对象的重要功能。这个小程序是虚基类的实现.
浅谈C++中virtual的三种用法
主要介绍了浅谈C++中virtual的三种用法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧


