【发布时间】: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 *>>
你知道为什么会这样吗?
【问题讨论】:
-
虽然
B是A(由于继承),但事实并非如此。继承是一种单向关系。 -
根据定义,
std::vector<B *>仅包含B *类型的元素。B *类型的变量(或元素)只能指向B或从B派生的类型的对象。A既不是B也不是派生自B的类型(因为B派生自A,而不是相反)。在不知道为什么您认为A*可以存储在std::vector<B *>中的情况下,不可能提供有关如何“修复它”的解决方案。 -
main 的前两行也包含错误。您还没有创建 A;只有一个指向 A 的指针。因此,第二行中的赋值,将分配给一些随机的可能未分配的内存地址。第一行应该是
A* first = new A();
标签: c++ pointers inheritance vector