gpt4 book ai didi

C++ 在具有不同对象类型的容器中管理 ifstream

转载 作者:搜寻专家 更新时间:2023-10-31 02:15:52 24 4
gpt4 key购买 nike

我在容器 animalColl 中创建了几个不同的 DogCat 对象。我正在尝试锻炼如何调整读取的文件流,以便如果容器中的对象是 Cat,则使用 catfile,而 Dog 使用 dogfile。目前,仅使用传递到参数中的 animalType。是否可以根据对象类型选择使用哪个文件流?

void Animal::load(std::string animalType)
{
std::string file = animalType + ".csv";
std::ifstream lstream(file);

for (Animal *a : animalColl)
{
a->load(lstream); //uses one stream to read all the different objects in container
}
}

最佳答案

不幸的是,我不确定您为什么要递归调用 load,所以我无法给出确切的答案。我认为您正在寻找的答案是使用多态性。这是一个基本示例:

动物.h

#ifndef ANIMAL_H
#define ANIMAL_H

#include <iostream>
#include <string>

class Animal
{
public:
void load()
{
std::string fileName = this->getAnimalFilename() + ".csv";
std::cout << "fileName = " << fileName << std::endl;
}

protected:
virtual std::string getAnimalFilename() { return "Animal"; }
};

#endif //ANIMAL_H

狗.h

#ifndef DOG_H
#define DOG_H

#include <string>
#include <iostream>

class Dog : public Animal
{

protected:
virtual std::string getAnimalFilename() { return "Dog"; }
};

#endif //DOG_H

猫.h

#ifndef CAT_H
#define CAT_H

#include <iostream>
#include <string>

class Cat : public Animal
{

protected:
virtual std::string getAnimalFilename() { return "Cat"; }
};

#endif //CAT_H

还有一个示例用法(请注意,您必须使用指向基类的指针来获得多态性的覆盖特性,并且您必须将函数声明为虚函数以在派生类中覆盖它)。

编辑:@ArchbishopOfBanterbury 指出,下面的 main.cpp 被编辑为使用智能指针,因为它使用原始指针并导致内存泄漏。

主要.cpp

#include <iostream>
#include <vector>
#include <string>
#include <memory>
#include "animal.h"
#include "dog.h"
#include "cat.h"

int main(int argc, char *argv[])
{
std::vector<std::unique_ptr<Animal>> animalColl;
animalColl.emplace_back(new Dog());
animalColl.emplace_back(new Cat());
animalColl.emplace_back(new Cat());
animalColl.emplace_back(new Dog());
for (auto &a : animalColl) {
a->load();
}

return 0;
}

输出:

fileName = Dog.csv
fileName = Cat.csv
fileName = Cat.csv
fileName = Dog.csv

基本思想是在使用指向基类的指针时使用关键字 virtual 来覆盖行为。因此,在我的示例中,getAnimalFilename 在 Dog 和 Cat 类中被重写以返回正确的字符串,而不是将其传递到 load() 函数中。这有帮助吗?请继续回复此评论,我会尽力提供帮助。

关于C++ 在具有不同对象类型的容器中管理 ifstream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37932776/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com