如何在C ++的基类向量中找到哪个派生类

how can find which derive class in vector of base class in c++

本文关键字:派生 向量 基类      更新时间:2023-10-16

我有一个基指针向量,需要知道这个基类的哪个派生类

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;
};