0

I'm trying to get my head around why I can't overwrite a subclass object with another subclass object if they share base class.

Say that Letter is the base class. A and B are subclasses. The following doesn't seem to work:

Letter* a_p = new A();
Letter* b_p = new B();

delete a_p;
*a_p = *b_p;

My ambition is to change what is located at a certain adress so that all pointers to the adress in question changes what they point to. In the above example, I'd like to somehow change the "content" of a_p to a copy of the "content" of b_p.

Is this possible somehow?

4

4 回答 4

4

如果您正在复制对象并且指针的类型是基类,那么您将丢失有关子类的所有信息。

而且由于您删除了a_p,*a_p=因此做错了,因为a_p指向不再分配的内存。

为什么不只是做:a_p = b_p;

于 2013-01-02T17:53:08.260 回答
2

在您给出的示例代码中,最突出的错误是您取消引用以前删除的指针。但是可以说那些是堆栈上的对象;

class Base
{
};

class A : public Base
{
};

class B : public Base
{
  int a;
};

int main()
{
  A a;
  B b;
  b = a; // This gives an error
  return 0;
}

我们试图将一个A对象复制到一个B具有不同内存布局(添加的 int 成员)的对象中。该成员将如何初始化,您认为!?出于同样的原因,您不允许有指向A的对象的指针B,它们是不同的类型。

这两种类型“相同”的唯一地方是您通过Base指针访问它们的地方。

于 2013-01-02T18:02:20.407 回答
1

A 和 B 在内存中的大小可能不同。此外,delete 释放分配给 a_p 的内存。您将写入未分配的内存。这将导致“未定义的行为”

于 2013-01-02T17:56:06.197 回答
0

如果您正在寻找分配指针值,我认为您是,那么您需要这样做

a_p = b_p

不是*a_p = *b_p

于 2013-01-02T17:52:38.217 回答