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

时间:2014-11-20 22:13:49

标签: 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文件在成员的私人文件中。 我怎样才能找到派生的类型?

3 个答案:

答案 0 :(得分:2)

听起来像多态性的工作:

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调用正确的版本。

答案 1 :(得分:0)

技术上你可以将虚拟析构函数放在最顶层的基类中,然后使用dynamic_cast尝试向下转换指针。

相反,我强烈建议您将相关的虚函数放在指针类中。

虚拟功能是一种进行类型安全,高效的向下转换的方法。通过例如手动降级dynamic_cast效率低,容易出错。

答案 2 :(得分:-2)

在这些情况下我做的是使用枚举。

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;
};
相关问题