2017-12-16 8 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(); 

私の問題は、両方の "for each"ですべての問題がリストされていることです。 これを行う方法はありますか?私は、サブクラスを識別する変数を追加したくありません。ベクター多型を持つ子供を単離する方法

+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; 
} 
関連する問題