【发布时间】:2015-07-04 06:33:21
【问题描述】:
我有一个超类Entry 和子类MusicAlbum、Book 和Film。这些子类的实例根据项目名称存储,即Book1。所有这些实例的名称和类型都存储在向量cat_vector 中,该向量是libCatalogue 类对象的向量,它只存储名称和类型:
class libCatalogue{
std::string name;
std::string type;
public:
libCatalogue(std::string name, std::string type);
std::string getname();
std::string gettype();
};
libCatalogue::libCatalogue(std::string name, std::string type) :name(name), type(type) {};
std::vector <libCatalogue> cat_vector;
向量中的条目是在构造函数中创建的,例如。
MusicAlbum::MusicAlbum(std::string a, std::string b, std::string borrower)
: name(a), artist(b), Entry(borrower){
cat_vector.push_back(libCatalogue(name, "MusicAlbum"));
每个子类都有一个名为printdetails() 的成员函数。我想使用循环遍历cat_vector 中的每个条目并打印条目的详细信息,但以下内容不起作用:
int no = 1;
for (auto it = begin(cat_vector); it != end(cat_vector); ++it)
{
std::string name_ = it->getname();
std::string type_ = it->gettype();
std::cout << "Entry no. " << no << std::endl;
std::cout << "Name: " << name_ << std::endl;
std::cout << "Type: " << type_ << std::endl << std::endl;
if (type_ == "MusicAlbum"){
name_.printdetails(); //print using MusicAlbum member function
}
//etc...
no++;
我知道这是因为name_ 是一个字符串,而不是我要调用的任何类的对象,但到目前为止我还没有找到任何转换它的方法。有什么方法可以告诉编译器name_ 指的是其中一个子类的对象?
【问题讨论】:
-
哪个类里面定义了print_details?
-
不,它是
std::string。包含的内容无关紧要。这听起来像libCatalogueshoudl me astd::multimap<std::string, std::shared_ptr<Entry>>,或类似的东西。我假设printdetails()是从Entry开始的虚拟或纯虚拟。 -
三个子类都有自己的 printDetails