如何与载体多态性分离儿童
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) { ... });
使用多态性时,我倾向于在基类中使用枚举标识符。Pro是您可以进行简单的整数比较,以查看派生类型是否为该类型。骗局是,如果某人想添加其他派生类型,则必须将新标识符注册到基础类枚举。
您的代码将看起来像这样:
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;
}
相关文章:
- 多态性和功能结合
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- C++boost序列化多态性问题
- 如何查找哪个类对象位于数组的特定索引上(多态性)
- 如何在多线程中正确使用unique_ptr进行多态性?
- 具有智能指针的多态性
- 在 C++ 中在堆栈上创建实例时如何保持多态性?
- 继承/多态性 - 我是否被迫使用"protected"变量?
- C++ 多态性在代码::块 17.12 中不起作用
- C++ 泛型和多态性:这种模式可行吗?
- 为什么我们实际上需要运行时多态性?
- 如何在这个简单的最小示例中实现多态性?
- 如何使用静态多态性在 int 和指针类型之间进行转换?
- 无法初始化已知大小的矢量指针,该大小不会因多态性而更改
- 运行时多态性和dynamic_cast需要澄清
- 如何调用指针类型的方法(禁用多态性)?
- 从基类调用函数的多态性
- 运行时多态性 - 箭头运算符访问了错误的成员?
- 如何与载体多态性分离儿童