派生类的地图 [英] map of derived classes
问题描述
我有一个基类
class Person {
public:
Person(string name, int age){
this - > name = name
this - >年龄=年龄
}
virtual void getInfo(){
cout<<< Person<<名称<< <年龄;
}
void add(string name,const Person& b){
a [name] = b
}
protected:
string name;
int age;
map< string,Person>一个;
};
包含对象类型Person的地图。我想将各种派生类推送到该地图中,例如
派生类
class Kid:public Person {
public:
Kid(string name,int age):Person(name,age){};
virtual void getInfo(){
cout<<< Kid<<名称<<< <年龄;
}
};
我想要$ code>添加 Person类的方法bahave如
Person one(John,25);
one.add(Suzie,15);
哪个失败。我知道我可以使用指针重写代码,例如
map< string,Person *> a
void add(string name,Person * b){
a [name] = b;
}
个人(约翰,25岁);
one.add(new Kid(Suzie,15))
一种如何实现它而不使用指针?
不,不能使用引用或指针,无法获取多态。 / p>
通过认为非指针对象需要存储整个类数据(包括vtable),这个问题很容易理解。
这意味着映射< string,person>
将在<$ c中存储个人
$ c> sizeof(person) slot。
但是一个 sizeof(person)
不能包含足够的数据来存储个人
的子类的附加信息。这导致对象切片。
I have a base class
class Person{
public:
Person(string name , int age ){
this -> name = name;
this -> age = age;
}
virtual void getInfo(){
cout << "Person " << name << " " << age;
}
void add(string name , const Person & b){
a[name] = b
}
protected:
string name;
int age;
map<string , Person > a;
};
That contains map of object type Person. I want to push various derived classes into that map e.g
Derived class
class Kid : public Person{
public:
Kid(string name, int age):Person(name,age){};
virtual void getInfo( ){
cout << "Kid " << name << " " << age;
}
};
I want add
method of Person class to bahave such as
Person one("John",25);
one.add("Suzie",15);
Which fails. I know i can remake the code using pointers e.g
map<string , Person*> a
void add( string name , Person *b){
a[name] = b;
}
Person one("John",25);
one.add(new Kid("Suzie",15))
But is there a way how to achieve it without using pointers?
No, you can't obtain polymorphism without using references or pointers.
The issue is easily understood by thinking that a non pointer object requires to store the whole class data (including the vtable).
This means that a map<string, person>
will store somewhere person
instances in a sizeof(person)
slot.
But a sizeof(person)
can't contain enough data to store additional information of subclasses of person
. This leads to object slicing.
这篇关于派生类的地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!