我的问题是我有一个基类和 3 个子类,我想制作一个向量,我可以在其中放置代表所有 3 个子类的所有元素。这是处理从文件中读取的代码部分
vector<Robot*> robots;
vector<Mac> mac;
vector<Eco> eco;
vector<Pro> pro;
vector<int> charge;
vector<int> deliver;
try {
string s;
ifstream f;
do {
cout << "Add meg a filenevet" << endl;
cin >> s;
f.open(s.c_str());
} while (!f.good());
cout << "adatok beolvasasa..." << endl;
int napok;
if (!(f >> napok)) throw 1;
charge.resize(napok);
deliver.resize(napok);
for (int i = 0; i<napok; i++) {
if (!(f>>charge[i])) throw 1;
if (!(f>>deliver[i])) throw 1;
}
string type, name;
int battery;
int m = 0; int e = 0; int p = 0;
std::string line;
while (std::getline(f, line)) {
stringstream ss(line);
if (ss >> type && ss >> name && ss >> battery) {
if (type=="Mac") {
cout << "mac" << endl;
Mac r = Mac(name,battery);
mac.push_back(r);
robots.push_back(&mac[m]);
m++;
};
if (type=="Eco") {
cout << "eco" << endl;
Eco r = Eco(name,battery);
eco.push_back(r);
robots.push_back(&eco[e]);
e++;
}
if (type=="Pro") {
cout << "pro" << endl;
Pro r = Pro(name,battery);
pro.push_back(r);
robots.push_back(&pro[p]);
p++;
};
}
}
到目前为止,这有效,它可以编译并且也可以运行,但是当我尝试访问某个函数时robots[i].getBattery();
,程序会冻结。似乎指针只是指向无处,但我不知道为什么:(