简体   繁体   English

复制继承类的指针向量的问题

[英]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:当我尝试将A*类型的元素push_back()B*类型的元素数组时,出现以下错误:

 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. B 是 A 但不是相反。

So it would have worked only if A inherited from B.所以只有当 A 从 B 继承时它才会起作用。

child class can be interpret as father class's pointer, reverse not work.子 class 可以解释为父类的指针,反向不起作用。

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 ); 
}

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

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