【问题标题】:Problem with copying a vector of pointers of inherited classes复制继承类的指针向量的问题
【发布时间】:2021-12-30 13:00:53
【问题描述】:

我有两个类,一个继承另一个:

#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
}

当我尝试将push_back() 类型为A* 的元素添加到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 *>>

你知道为什么会这样吗?

【问题讨论】:

  • 虽然BA(由于继承),但事实并非如此。继承是一种单向关系。
  • 根据定义,std::vector&lt;B *&gt; 仅包含 B * 类型的元素。 B * 类型的变量(或元素)只能指向B 或从B 派生的类型的对象。 A 既不是 B 也不是派生自 B 的类型(因为 B 派生自 A,而不是相反)。在不知道为什么您认为A* 可以存储在std::vector&lt;B *&gt; 中的情况下,不可能提供有关如何“修复它”的解决方案。
  • main 的前两行也包含错误。您还没有创建 A;只有一个指向 A 的指针。因此,第二行中的赋值,将分配给一些随机的可能未分配的内存地址。第一行应该是 A* first = new A();

标签: c++ pointers inheritance vector


【解决方案1】:

你不能这样做。

B 是 A 但不是相反。

所以只有当 A 从 B 继承时它才会起作用。

【讨论】:

    【解决方案2】:

    子类可以解释为父类的指针,反向不行。

    正确的可能是:

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

    【讨论】:

      猜你喜欢
      • 2016-09-02
      • 2017-12-28
      • 1970-01-01
      • 2016-04-30
      • 1970-01-01
      • 2021-05-24
      • 2017-07-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多