gpt4 book ai didi

c++ - 如何调用确切的派生类方法?

转载 作者:太空宇宙 更新时间:2023-11-04 15:12:01 24 4
gpt4 key购买 nike

继续我之前的问题: How to return derived type?

I have a Validator class and derived classes from it; When i'm trying to return pointer to derived class then method return base class(Validator) instead of Derived.

我修改了我的类如下:

class Validator
{
public:
std::string m_name = "BaseValidator";

static const std::map<std::string, Validator *> validators();

void validateModel(Model &model, const std::vector<std::string> &attrNames);
static Validator *getByName(std::string &name);

virtual void validateAttribute(Model &model, const std::string &attribute);
virtual ~Validator();

virtual std::string name() const;
};

const std::map<std::string, Validator*> Validator::validators()
{
std::map<std::string, Validator*> result;
result["required"] = new RequiredValidator();
return result;
}

void Validator::validateModel(Model &model, const std::vector<std::string> &attrNames)
{
validateAttribute(model, name.at(0));
}

Validator* Validator::getByName(std::string &name)
{
auto g_validators = Validator::validators();
auto validator = g_validators.find(name);
if(validator != g_validators.end()){
return validator->second;
}else{
std::cerr << "Unknow type of validator: " << name << std::endl;
}
return nullptr;
}

void Validator::validateAttribute(Model &model, const std::string &attribute)
{
(void)model;
(void)attribute;
std::cout << this->name() << std::endl;
}

//------------------

class RequiredValidator : public Validator
{
public:
std::string m_name = "RequiredValidator";

void validateAttribute(Model &model, std::string &attribute);
~RequiredValidator();
std::string name() const;
};


std::string RequiredValidator::name() const
{
return m_name;
}

void RequiredValidator::validateAttribute(Model &model, std::string &attribute)
{
(void) model;
(void) attribute;
std::cout << "RequiredValidator!!!" << std::endl;
}

RequiredValidator::~RequiredValidator()
{

}


//------------------

auto validator = Validator::getByName("required");

validator->name();// will output RequiredValidator

//next i'm calling

validator->validateModel(); // whos calling validateAttribute() inside
//and it's output Validator::validateAttribute() //but i wan't
//RequiredValidator::validateAttribute();
//where i was wrong with logic???

The same virtual method name() working as i want, but validateAttribute() called from base class only.

最佳答案

仔细看看你是如何定义 void RequiredValidator::validateAttribute()

您可能会注意到签名与基本签名略有不同(std::string &attribute 不是 const)

有一个关键字 override 可以帮助编译器捕获这些类型的打字错误。

关于c++ - 如何调用确切的派生类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54196728/

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