gpt4 book ai didi

c++ - 如何通过字符串动态调用类函数

转载 作者:行者123 更新时间:2023-11-28 04:15:25 24 4
gpt4 key购买 nike

我想知道如何动态调用类函数。假设我有一个类“dog”,其中包含函数 getname(),它返回该特定动物的名称。但是我怎么能像那样调用函数 dog::getname() 但在开头没有“狗”我会使用 std::string animal = “dog”,然后以某种方式像 animal::getname()

我还没有尝试过任何东西,因为我根本不知道我怎样才能得到类似的结果,或者这是否可能。

class dog {
public:
static std::string getname() {
return "Something";
}
}

class cat {
public:
static std::string getname() {
return "Something2";
}
}

std::string animal = "dog";

现在以某种方式调用与字符串中的动物相关的函数 getname。

最佳答案

你在寻找多态性吗?

#include <memory>
#include <string>

// An animal interface for all animals to implement
class Animal {
public:
virtual ~Animal() = default;

virtual std::string getName() const = 0;
};

// An implementation of the animal interface for dogs
class Dog final : public Animal {
public:
std::string getName() const override {
return "John";
}
};

// An implementation of the animal interface for cats
class Cat final : public Animal {
public:
std::string getName() const override {
return "Angelina";
}
};

int main() {
std::unique_ptr<Animal> animal0 = std::make_unique<Dog>();
std::unique_ptr<Animal> animal1 = std::make_unique<Cat>();
// You can pass around a std::unique_ptr<Animal> or Animal *
// just as you would pass around a string.
// Although, std::unique_ptr is move-only
std::cout << animal0->getName() << '\n';
std::cout << animal1->getName() << '\n';
}

关于c++ - 如何通过字符串动态调用类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56745077/

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