[英]How to isolate a child with vector polymorphism
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();
我的問題是,在所有“針對每個”問題上,都列出了所有問題。 有沒有辦法做到這一點? 我不想添加一個標識子類的變量。
在這種情況下,您需要使用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) { ... });
使用多態時,我傾向於在基類中使用枚舉標識符。 這樣做的好處是,您可以進行簡單的整數比較,以查看派生類型是否是該類型。 不利的一面是,如果有人想添加另一個或新的派生類型,則必須向基類枚舉注冊一個新的標識符。
您的代碼將如下所示:
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.