用c++编写有一个基类两个子类的派生类
2013-05-21
展开全部
子类就是派生类,不明白你到底要啥?
eg:
基类A,类B直接继承于友首A,类C直接继承于B;
then:
类A派生类B,类A被类B继承;类B派生类C, 类B被类C继承;
类B是类A的子类,类C是类B的子类;
类B和类C都是类A的派生类;
再比如:
#include <iostream>
using namespace std;
class MusicTeacher
{
public:
MusicTeacher(){m_music=0;};
MusicTeacher(const int& m){m_music=m;};
void set_music(const int& m){m_music=m;};
int music(){return m_music;};
int m_music;
};
class SingingTeacher: virtual public MusicTeacher
{
public:
SingingTeacher(){m_song=0.0;};
SingingTeacher(const float& f):m_song(f){MusicTeacher((int)f);};
float music(const float& f){m_song+=m_music;return m_song+=f;};
float song(){return m_song;};
float m_song;
};
class DanceTeacher: virtual public MusicTeacher
{
public:
DanceTeacher(){m_dance=0.0;};
DanceTeacher(const double& d):m_dance(d){MusicTeacher((int)d);};
double music(const double& d){m_dance+=m_music;return m_dance+=d;};
double dance(){return m_dance;};
double m_dance;
};
class VersatileStudent: virtual public SingingTeacher, virtual public DanceTeacher
{
public:
VersatileStudent(){};
VersatileStudent(const int& i){};
VersatileStudent(const float& f){};
VersatileStudent(const double& d){};
};
int main(int argc, char* argv[]){
VersatileStudent s;
SingingTeacher* st=&s;
DanceTeacher* dt=&s;
MusicTeacher *mt=&s;
s.SingingTeacher::m_music=1;//1
cout<<s.m_music<<endl;
s.DanceTeacher::m_music=2;//2
cout<<s.m_music<<endl;
cout<<mt->music()<<endl;//2
mt->set_music(3);
cout<<谨仿s.m_music<<endl;//3
cout<<st->song()<<endl;//0
cout<<s.SingingTeacher::music((float)0.1)<<endl;//3.1
cout<<st->music((float)0.1)<<endl;//6.2
cout<<dt->dance()<<endl;//0
cout<<s.DanceTeacher::music(0.2)<<endl;//3.2
cout<好晌数<dt->music(0.2)<<endl;//6.4
return 0;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询