C++ 如何避免这种狭窄?

C++ 如何避免这种狭窄?,c++,C++,我有两个基类和派生类。派生类继承基类。让Base有一个名为i的变量。并且派生有一个变量派生_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

我有两个基类和派生类。派生类继承基类。让Base有一个名为i的变量。并且派生有一个变量派生_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,并在不影响b的情况下删除a。我尝试使用一个局部临时变量

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.
这意味着衍生零件没有正确复制,因此发生错误

在这一行中:

Base tmp = *a;
如果*a的类型是派生的,那么它将被切分到基。你可以试试这个:

Base *b = new Derived(*a);
你会发现信息量很大。