如何在父类中调用子类?
class Society
{
void add_student(string name,string home_town)//add student to society
{
Student a;
a.set_name(name);
a.set_home_town(home_town);
}
bool same_community(Student s1, Student s2){}//check if student 1 & student 2 are in the same community
void join_communities(Student s1,Student s2){}//join communities which student 1 & student 2 are in
int num_of_communities(){}//return the total number of communities inside the society
float max_diversity(){}//return the highest diversity between all communities
};
class Community : public Society
{
void add(Student new_student){}//add new student to community
bool contains(string name_student){}//whether community contains a student named name_student
void join(Community other_community){}//add all students in other_community to this community
float diversity(){}//return the number of distinct hometowns/names for this community
};
class Student :public Community
{
string name, string home_town;
public:
void set_name(string a){name=a;}
void set_home_town(string b){home_town=b;}
string get_name() const{return name;}
string get_home_town() const{return home_town;}
};
我有一个名为 Society 的父类,我想在某些函数中使用其名为 Student 的子类。我该怎么做?
class Society
{
void add_student(string name,string home_town)//add student to society
{
Student a;
a.set_name(name);
a.set_home_town(home_town);
}
bool same_community(Student s1, Student s2){}//check if student 1 & student 2 are in the same community
void join_communities(Student s1,Student s2){}//join communities which student 1 & student 2 are in
int num_of_communities(){}//return the total number of communities inside the society
float max_diversity(){}//return the highest diversity between all communities
};
class Community : public Society
{
void add(Student new_student){}//add new student to community
bool contains(string name_student){}//whether community contains a student named name_student
void join(Community other_community){}//add all students in other_community to this community
float diversity(){}//return the number of distinct hometowns/names for this community
};
class Student :public Community
{
string name, string home_town;
public:
void set_name(string a){name=a;}
void set_home_town(string b){home_town=b;}
string get_name() const{return name;}
string get_home_town() const{return home_town;}
};
I have a parent class named Society and I would like to use its child class named Student in some of the functions.how can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我同意其他评论,但如果有必要,您可以使用此表单应用 CRTP 模式。但是,此解决方案仅适用于学生社区,您不能混合不同的社区成员:
I agree with other comments, but if necessary, you can apply CRTP pattern with this form. However, this solution only apply to Student communities, you can't mix different community members: