访问映射中元素的成员,该映射的值是C ++中的抽象基类

时间:2013-07-06 10:23:45

标签: c++ map polymorphism

英文说明:我想从foo "bar" std::map<string, Parent *>的{​​{1}}密钥元素访问名为Parent的成员是一个抽象的基类。

代码:

#include <map>
#include <string>
#include <iostream>

using namespace std;

class Parent {
public:
    virtual ~Parent() {}
};

class Child: public Parent {
public:
    Child(): var(2) {}
    int var;
};

int main() {
    map<string, Parent *> children;
    children["bar"] = new Child;
    cout << children["bar"]->var << endl; // Erroneous line
    cout << children.find("bar")->second->var << endl; // Different method, still gives the same error
    return 0;
}

错误: ‘class Parent’ has no member named ‘var’

我也尝试过使用boost::ptr_map

int main() {
    boost::ptr_map<string, Parent> children;
    string key = "bar";
    children.insert(key, new Child);
    cout << children.find(key)->second->var << endl; // Same error :(
    return 0;
}

1 个答案:

答案 0 :(得分:5)

您无法使用var指针访问Parent,因为Parent::var不是一个问题。相反,试试这个:

class Parent {
public:
    virtual ~Parent() {}
    virtual int getVar() const = 0;
};

class Child: public Parent {
public:
    Child(): var(2) {}
    virtual int getVar() const { return var; }
private:
    int var;
};

int main() {
    map<string, Parent *> children;
    children["bar"] = new Child;
    cout << children["bar"]->getVar() << endl; // Erroneous line
}