2014-07-13 48 views
1

我有两个类“Base”和“Derived”。派生继承基类。让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; 

现在我要的值分配给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. 

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

+0

你会发现[这个问题及其最佳答案](http://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c)相当丰富。 – WhozCraig

回答

0

在这一行:

Base tmp = *a; 

如果*a是派生类型,它被切下来Base。你可以试试这个:

Base *b = new Derived(*a);