|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 你咋这么牛逼呢 于 2016-2-14 13:04 编辑
#include<iostream>
#include<string>
class People
{
public:
People(std::string pname);
void pro();
protected:
std::string name;
};
class Student :virtual public People//虚继承语法 在前面加上virtual关键字
{
public:
Student(std::string sname,std::string cname);
void spro();
protected:
std::string classstudent;
};
class Teacher :virtual public People
{
public:
Teacher(std::string tname,std::string cname);
void tpro();
protected:
std::string classteacher;
};
class Ts : public Teacher,public Student
{
public:
Ts(std::string pname,std::string tname,std::string sname);
};
People::People(std::string pname)
{
name=pname;
}
void People::pro()
{
std::cout<<"我的名字叫"<<name<<'\n';
}
Student::Student(std::string sname,std::string cname) : People(sname)
{
classstudent=cname;
}
void Student::spro()
{
People::pro();
std::cout<<"我是一个学生,我在"<<classstudent<<'\n';
}
Teacher::Teacher(std::string tname,std::string cname) : People(tname)
{
classteacher=cname;
}
void Teacher::tpro()
{
People::pro();
std::cout<<"我是一名老师,我教"<<classteacher<<'\n';
}
Ts::Ts(std::string pname,std::string tname,std::string sname) : Teacher(pname,tname),Student(pname,sname),People(pname)
{
//此处为什么多个poeple(name)才能通过 //前面的teacher和student的构造器中不是已经继承了people的
//构造器对基类people初始化了吗
}
int main()
{
Teacher t("小方","304班");
Student s("小红","005班");
Ts ts("小智","005班","304班");
t.tpro();
s.spro();
ts.spro();
ts.tpro();
return(0);
}
因为是虚继承,只能保存一份来自基类的属性拷贝,再次继承的子类没有该属性了,所以只能继承People来获得该属性
应该是吧
|
|