据说,通过多态性,我们可以使用其基类对象访问派生类成员字段,如下所示:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Tool{
public:
Tool(){}
Tool(string name){
this->name = name;
}
virtual string getInfo(){
return name;
}
//protected:
string name;
};
class Computer: public Tool{
public:
Computer(string name, int price){
this->name = name;
this->price = price;
}
virtual string getInfo(){
return name + ": " + to_string(static_cast<long long>(price));
}
//protected:
int price;
};
class Person{
public:
Person(){}
Person(string name){
this->name = name;
}
virtual string getInfo(){
return name;
}
virtual void addTools(Computer cmp){
tools.push_back(cmp);
}
//protected:
vector<Tool> tools;
string name;
};
class Programmer: public Person{
public:
Programmer(string name, string job){
this->name = name;
this->job = job;
}
string getInfo(){
return name + ": " + job;
}
//protected:
string job;
};
int main(){
Person prs("Person");
Programmer prg("Daphloon", "programmer");
Person* prs1 = &prs;
Person* prs2 = &prg;
cout << prs1->getInfo() << endl; // result: Person
cout << prs2->getInfo() << endl; // result: Daphoon: programmer
Tool tl("Hammer");
Computer cmp("PC", 100);
Tool* tl1 = &tl;
Tool* tl2 = &cmp;
cout << tl1->getInfo() << endl; // result: Hammer
cout << tl2->getInfo() << endl; // result: PC: 100
prs2->addTools(cmp);
cout << prs2->tools[0].getInfo() << endl; // result: PC
// I expect the result will be: PC: 100
return 0;
}
结果不是我想象的那样。我需要的是 Person
的每个派生类都有一个 vector tools
,其中包含从 Tool
类继承的对象。如果用文字描述,则会是“这个人
,一个程序员
,有一些工具
。他的第一个工具
是一台计算机
。如果您想知道它的价格
,请使用getInfo()
。”
- 为什么 vector 采用基类而不是派生类?
- 当我将
cmp
对象放入tools
vector 中时,它是否会丢失任何数据? - 发生这种情况是因为
tools
vector 成员采用Tool
作为其类型吗?
最佳答案
C++ 中的运行时多态性通过虚拟函数实现,适用于 covariant类型。唯一的协变类型是指针和引用。既然你有 vector<Tool>
,你就失去了多态性。要保留它,请存储 vector<Tool*>
。更好的是,存储 vector<unique_ptr<Tool>>
.
将派生类对象分配给基类称为object slicing 。您确实会丢失派生对象中包含的信息。当您插入 Computer
时就会出现这种情况。进入vector<Tool>
.
关于c++ - 如何使用多态性从基类访问派生类 vector 成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27644872/