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的子类。我可以这样做吗?
答案 0 :(得分:0)
我同意其他评论,但如有必要,您可以在此表单中使用CRTP pattern。但是,此解决方案仅适用于学生社区,您不能混合不同的社区成员:
template<typename T>
class Society
{
void add_student(string name,string home_town)
{
T student;
student.set_name(name);
......
}
....
};
template <typename T>
class Comunity : public Society<T>
{
void add(T new_student){}//add new student to community
....
};
class Student : public Comunity<Student>
{
.....
}