如何在C ++的基类向量中找到哪个派生类
how can find which derive class in vector of base class in c++
我有一个基指针向量,需要知道这个基类的哪个派生类
class Document {
protected :
string name;
Date date_borrow; // Date is class
};
class Book : public Document {
private :
int book_pages;
};
class Reference : public Document {
private :
string writer;
};
class Member {
protected :
vector < Document* > document;
};
class Library {
public :
void borrow ( Member* member, Document* document ){
member->add_document ( document );
}
private :
vector < Document* > documents;
vector < Member* > members;
};
在这个代码中,当成员借用文档时,我需要知道文档*是一本书或参考书来计算迟到的罚款。(惩罚的功能因书籍和参考而异)然后在成员私下push_back文档中的文档。如何找到派生的类型?
听起来像是多态性的工作:
class Document {
public:
virtual ~Document() { }
virtual double latePenalty() = 0;
};
class Book : public Document {
public:
double latePenalty() {
// book-specific late penalty
return 5.0 * daysLate() + 17.0;
}
};
class Reference: public Document {
public:
double latePenalty() {
// reference-specific late penalty
return 1e6; // because that'll teach you!
}
};
vector < Document* > documents;
这样,调用latePenalty()
将通过动态调度为每种类型的Document
调用正确的版本。
从技术上讲,您可以将虚拟析构函数放在最顶层的基类中,然后使用 dynamic_cast
尝试向下转换指针。
相反,我强烈建议您将相关的虚函数放在 pointee 类中。
虚函数是一种执行类型安全、高效下播的方法。手动向下铸造,例如 dynamic_cast
效率低下且容易出错。
在这些情况下,我所做的是使用枚举。
enum document_type { dtBook, dtReference };
然后每个类都有一个如下所示的成员:
class Document {
protected:
std::string name;
Date date_borrow; // Date is a class
public:
virtual document_type GetType() = 0;
// note that this makes the class pure virtual. If that is undesirable,
// you might want to add a third type to the enum, like dtDocument, as
// a default return value
};
class Book : public Document {
document_type GetType() {
return dtBook;
};
private:
int book_pages;
};
class Reference : public Document {
document_type GetType() {
return dtReference;
};
private:
std::string writer;
};
相关文章:
- 如何通过派生类函数更改基类中的向量
- 有没有一种"cleaner"的方法可以在指向基的指针向量中找到派生类的第一个实例?
- 如何创建派生对象的向量?
- 将shared_ptr的向量复制到抽象基的派生类
- 基类到派生类的强制转换向量
- 创建基类指针的向量并将派生类对象传递给它(多态性)
- 有没有办法复制派生类指针的向量而不将其强制转换为基类?
- 无法将派生类存储在基类指针的向量中
- 在 c++ 中,如何使用向量调用派生类?
- 基类类型向量中的派生结构
- 按类型排序向量并按类型或派生类型搜索
- 替换派生对象向量中的对象"no matching function to call"
- 用于填充 Base 和派生对象的 shared_ptr 向量的函数模板
- 使用 shared_ptr 的派生类对象的向量
- 指向派生类的向量的指针
- 如何在另一个类的向量中调用派生类的析构函数
- 将抽象派生类对象存储在基类向量中
- 使用 boost::序列化将派生类指针序列化为向量时出现问题
- 向量类和派生向量类之间的区别
- 派生向量:执行操作