2011-10-16 2 views
1
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

기본 클래스는 클래스에서 파생되는 클래스를 알 수 없습니다. 이제까지. 대신 [방문자 패턴] (http://en.wikipedia.org/wiki/Visitor_pattern)을 찾아보십시오. –

+2

그건 그렇고, 학생은 어떤면에서 커뮤니티입니까? 상속 나무가 망가져있는 것 같습니다. –

답변

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> 
{ 
    ..... 
} 
관련 문제