简体   繁体   中英

Problem with copying a vector of pointers of inherited classes

I have two classes, one inherits the other:

#include <iostream>
#include <vector>

class A
{
public:
    int a;
};

class B : public A
{
    void print()
    {
        std::cout << a;
    }
};

int main()
{
    A* first;
    first->a = 5;
    std::vector<B*> second;
    second.push_back( first ); // the error appears at this line
}

When I try to push_back() an element of type A* to the array of elements of type B* , the following error appears:

 no instance of overloaded function "std::vector<_Ty, _Alloc>::push_back [with _Ty=B *, _Alloc=std::allocator<B *>]" matches the argument list
  argument types are: (A *)
  object type is: std::vector<B *, std::allocator<B *>>

Do you have any idea why this is happening?

You can't do this.

B is an A but not the reverse.

So it would have worked only if A inherited from B.

child class can be interpret as father class's pointer, reverse not work.

corret one may be:

#include <iostream>
#include <vector>

class A
{
public:
    int a;
};

class B : public A
{
    void print()
    {
        std::cout << a;
    }
};

int main()
{
    B* first;
    first->a = 5;
    std::vector<A*> second;
    second.push_back( first ); 
}

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