不幸的是,我不确定您为什么要递归调用 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 被编辑为使用智能指针,因为它使用原始指针并导致内存泄漏。
main.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 来覆盖行为。因此,在我的示例中,在 Dog 和 Cat 类中覆盖 getAnimalFilename 以返回正确的字符串,而不是将其传递给 load() 函数。这有帮助吗?继续回复此评论,我会尽力提供帮助。