简体   繁体   中英

New to C++ pointers; trying to retrieve a child's object from a vector of a pointer to the parent class. Help would be appreciated

So, I'm trying to create an entity management system in which one container has access to many and varying types of objects. I'm having some difficulties, and would appreciate any help that the Stack Overflow community can lend. Cheers in advance.

int main() {
    std::vector<std::unique_ptr<Prop>> x;
    Prop y;
    Actor z; // has actor-only "xyz" property (string);
    x.emplace_back(y); // 0
    x.emplace_back(z); // 1
    std::cout << (Actor)x[1].get()->xyz;
    return 0;
}

If you are using C++17 and speed is not the main focus at the moment, you could take a look at std::variant . It is a union that can hold almost any type, as long it fullfils its requirements.

In your example above you are not dealing much with pointers. Watch out for the terminology, although unique_ptr contains the word ptr , in the classical sense the reader might expect you are talking about raw-pointers . unique_ptr is a smart pointer that owns and manages the object on its own.

MVCE: https://gcc.godbolt.org/z/-zUUbK

#include <vector>
#include <variant>

class Foo {};
class Bar {};

using FooBarVector = std::vector<std::variant<Foo, Bar>>;

int main()
{
    FooBarVector objects = {Foo(), Bar()};
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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