
[英]How to reference derived objects in a vector of pointers to base class objects?
[英]Pointers to derived class objects stored in a vector of pointers to base class objects [closed]
我必须从文件中读取并根据我正在读取的文件行实例化对象。
该文件具有以下格式:
num1 RandomString RandomString num2 num3 num4<br>
num1 RandomString RandomString<br>
num1 RandomString RandomString num2 num3 num4<br>
num1 标识我需要实例化的 object 的类型。 例如,如果 num1 是 1,那么我需要创建一个狗 object,如果是别的,那么我需要创建一个通用动物 object。
下面的代码已经完成了一半。
注意:目前我还没有为将成员设为私有而烦恼。 现在不是优先事项。
#include <vector>
etc...
class Animal {
public:
int num1;
string 1;
string 2;
int num2;
int num3;
int num4;
std::string restOfTheLine;
Animal(fLine){
std::stringstream stream(fLine)
stream >> num1;
std::getline(stream, restOfTheLine);
getFunctions etc...
}
class Dog : public Animal{
}
int main(){
ifstream file("file.txt");
std::string line;
std::vector<Animal*> animals;
while(!file.eof()){
std::getline(file,line);
if(line[0]=='1'){
Dog* dog = new Dog(line);
animals.push_back(dog);
}
else{
Animal* animal = new Animal(line);
animals.push_back(animal);
}
std::cout << animals[2]->getNum2();
}
所以我正在检查该行的第一个字符是否为 1。如果是,则必须实例化一条狗 object。
当我编译它给我一个错误 - error:no matching function for call dog::dog
,这显然是因为我没有在派生的狗 class 中写任何东西,因为我不确定如何处理它。
我有一个指向动物的指针类型的向量,那么如何使用 inheritance 添加指向狗的指针?
您正在尝试调用不存在的Dog()
构造函数,就像错误消息告诉您的那样。 所以只需添加这样一个构造函数。
您还需要Animal
中的virtual
析构函数,以便通过Animal*
指针正确销毁Dog
object。
尝试这个:
#include <fstream>
#include <vector>
#include <string>
...
using namespace std;
class Animal {
public:
...
Animal(const string &fLine) {
...
}
virtual ~Animal() {}
...
};
class Dog : public Animal{
public:
Dog(const string &fLine) : Animal(fLine) {}
};
int main() {
ifstream file("file.txt");
std::string line;
std::vector<Animal*> animals;
while (std::getline(file, line)) {
if (line.empty()) continue;
if (line[0] == '1') {
animals.push_back(new Dog(line));
}
else {
animals.push_back(new Animal(line));
}
...
}
for(size_t i = 0; i < animals.size(); ++i) {
delete animals[i];
}
return 0;
}
如果您使用 C++11 或更高版本,请考虑使用std::unique_ptr
为您管理 object 破坏:
#include <fstream>
#include <vector>
#include <string>
#include <memory>
...
using namespace std;
class Animal {
public:
...
Animal(const string &fLine) {
...
}
virtual ~Animal() {}
...
};
class Dog : public Animal{
public:
Dog(const string &fLine) : Animal(fLine) {}
};
int main() {
ifstream file("file.txt");
std::string line;
std::vector<std::unique_ptr<Animal>> animals;
while (std::getline(file, line)) {
if (line.empty()) continue;
if (line[0] == '1') {
// if using C++11:
animals.push_back(std::unique_ptr<Animal>(new Dog(line)));
// if using C++14 and later:
animals.push_back(std::make_unique<Dog>(line));
}
else {
// if using C++11:
animals.push_back(std::unique_ptr<Animal>(new Animal(line)));
// if using C++14 and later:
animals.push_back(std::make_unique<Animal>(line));
}
...
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.