2017-12-16 27 views
0
class problem 
{ 
public: 
virtual void show() =0; 
} 

class wound : public problem 
{ 
public: 
void show(); 
} 

class disease: public problem 
{ 
public: 
void show(); 
} 

vector<problem*> lstProb; 

// I want to show all wounds only, no diseases yet 
for each (wound* ouch in lstProb) 
    ouch->show(); 

// Here only the diseases 
for each (disease* berk in lstProb) 
    berk->show(); 

내 문제는 "모두 각각"에 모든 문제가 나열되어 있다는 것입니다. 그럴 수있는 방법이 있습니까? 하위 클래스를 식별하는 변수를 추가하고 싶지 않습니다.벡터 다형성으로 아이를 분리하는 법

+0

:

코드는 다음과 같이 보일 것입니다. –

답변

0

벡터에있는 파생 형식을 보장 할 수 없기 때문에 dynamic_cast를 사용해야합니다. 이 같은

뭔가 작동합니다

template <class DerivedType, class BaseType, class F> 
void for_each(vector<BaseType *> elems, F && f) { 
    for (auto elem : elems) 
     if (auto ptr = dynamic_cast<DerivedType*>(elem)) 
      f(elem); 
} 

//usage 
for_each<Wound>(allelems, [](Wound * w) { ... }); 
for_each<Disease>(allelems, [](Disease * d) { ... }); 
0

내가 기본 클래스 내에서 열거 식별자를 사용하는 경향이 한 다형성 작업. 이 프로에서는 파생 형식이 해당 형식인지 확인하기 위해 간단한 정수 비교를 수행 할 수 있습니다. 반대면은 다른 파생 된 유형을 추가하려는 경우 기본 클래스 enum에 새 식별자를 등록해야한다는 것입니다. 당신은 dynamic_cast는 사용할 수

class Problem { 
public: 
    enum Type { 
     WOUND, 
     DISEASE 
    }; 

protected: 
    Type type_; 

public: 
    virtual void show() = 0; 
    Type getType() const { 
     return type_; 
    } 

protected: 
    explicit Problem(Type type) : type_(type) {} 
}; 

class Wound : public Problem { 
public: 
    static unsigned counter_; 
    unsigned id_; 

    Wound() : Problem(Type::WOUND) { 
     counter_++; 
     id_ = counter_; 
    } 

    void show() override { 
     std::cout << "Wound " << id_ << "\n"; 
    } 
}; 
unsigned Wound::counter_ = 0; 


class Disease : public Problem { 
public: 
    static unsigned counter_; 
    unsigned id_; 

    Disease() : Problem(Type::DISEASE) { 
     counter_++; 
     id_ = counter_; 
    } 

    void show() override { 
     std::cout << "Disease " << id_ << "\n"; 
    } 
}; 
unsigned Disease::counter_ = 0; 

int main() { 
    std::vector<Problem*> Probs; 

    // Add 10 of each to the list: types should be alternated here 
    // Vector<Problem> should look like: { wound, diesease, wound, disease...} 
    for (unsigned i = 0; i < 10; i++) { 
     //Wound* pWound = nullptr; 
     //Disease* pDisease = nullptr; 

     Probs.push_back(new Wound); 
     Probs.push_back(new Disease); 
    } 

    for (auto ouch : Probs) { 
     if (ouch->getType() == Problem::WOUND) { 
      ouch->show(); 
     } 
    } 

    std::cout << "\n"; 

    for (auto berk : Probs) { 
     if (berk->getType() == Problem::DISEASE) { 
      berk->show(); 
     } 
    } 

    // clean up memory 
    for each (Problem* p in Probs) { 
     delete p; 
    } 

    std::cout << "\nPress any key and enter to quit." << std::endl; 
    char c; 
    std::cin >> c; 

    return 0; 
}