简体   繁体   English

如何使用基本 class 作为 C++ 中派生类的占位符?

[英]How do I use a base class as a placeholder for derived classes in C++?

I'm looping through some code to populate some objects.我正在循环一些代码来填充一些对象。 I've spent too long trying to simplify the loop but I got stuck on using a base class as a placeholder for derived classes.我花了太长时间试图简化循环,但我坚持使用基础 class 作为派生类的占位符。 I feel like it should be possible, but I can't make it work.我觉得它应该是可能的,但我不能让它工作。

I'm running through a map, looking for specific strings in the value.我正在运行 map,寻找值中的特定字符串。 If I find one such string, I strip it down and store the data it contains in an object.如果我找到一个这样的字符串,我将其剥离并将其包含的数据存储在 object 中。 Depending on the string, I need the information stored in different subclasses (probably 5-7 subclasses).根据字符串,我需要存储在不同子类(可能是 5-7 个子类)中的信息。 I feel like I can shorten it further without losing readability, by using the parent object as the temporary object and defining it only once inside the for-loop, but I can't figure out how.我觉得我可以通过使用父 object 作为临时 object 并在 for 循环中只定义一次,从而在不失去可读性的情况下进一步缩短它,但我不知道如何。 The.push_back() function won't work if I do all_object_As.push_back(parent_object).如果我执行 all_object_As.push_back(parent_object),.push_back() function 将不起作用。

The store_data() function is only defined in the parent class. store_data() function 仅在父 class 中定义。

std::vector<Derived_object_A> all_object_As;
std::vector<Derived_object_B> all_object_Bs;    

for (auto element : some_map)
{
    std::vector<string> data_buffer = separate_data(get_data(element.second));

    if (element.second.find("SOMETEXT") != string::npos)
    {
        Derived_object_A object;
        object.store_data(data_buffer);

        all_object_As.push_back(object);
    }

    if (element.second.find("SOMEOTHERTEXT") != string::npos)
    {
        Derived_object_b object;
        object.store_data(data_buffer);

        all_object_Bs.push_back(object);
    }
}

The natural approach would be to replace:自然的方法是替换:

std::vector<Derived_object_A> all_object_As;
std::vector<Derived_object_B> all_object_Bs; 

with

std::vector<Base_object&> all_objects;

but you can't have a vector of references.但你不能有一个参考vector So, that leaves you with various approaches:因此,这为您提供了各种方法:

std::vector<Base_object*> all_objects_ptr; // but then you need to manage ownership and lifetimes
std::vector<std::shared_ptr<Base_object>> all_objects_shared_ptr;

There's probably a way with reference_wrapper too. reference_wrapper也可能有一种方法。

What's best for you is probably opinion-based and would require seeing more code, anyway.最适合您的可能是基于意见的,并且无论如何都需要查看更多代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM