如何避免这种缩小?

时间:2014-07-13 03:51:21

标签: c++

我有两个课程" Base"和"派生"。 Derived继承Base类。让Base有一个名为" i"的变量。 Derived有一个变量" derived_i"。

class Base
{
public:
  int i;
};

class Derived : public Base
{
public:
  int derived_i;
};

在以下代码中,

Base *a;
... // Some code operating on a.
// Now "a" points to an object of type "Derived". So,
cout << a->i; // Displays 2.
cout << ((Derived *)a)->derived_i; // Displays 3.

Base *b;

现在我必须将a的值分配给b并删除&#34; a&#34;不影响b。我尝试使用本地临时变量

Base *b;
Base tmp = *a;
delete a;
b = new Base(tmp);
// But, narrowing occured and,
cout << b->i; // This prints 2.
cout << ((Derived *)b)->derived_i; // This did not print 3.

这意味着派生部分没有正确复制,因此发生错误。

1 个答案:

答案 0 :(得分:0)

在这一行:

Base tmp = *a;

如果*a是派生类型,则会将其切成Base。你可以试试这个:

Base *b = new Derived(*a);