0

Say I have an array of pointers to an abstract class:

Piece *pieces[2]; // where piece is an abstract class

And I have two classes that extend Piece called King and Queen. I assign a King to a spot in pieces and Queen to another spot:

pieces[0] = new King();
pieces[1] = new Queen();

If I haven't overloaded the assignment operator, does slicing occur? Or does pieces[0] is an instance of King and pieces[1] is an instance of Queen? What is going on in that array (if this was C++)?

EDIT: See a full example of the code in question here.

4

3 回答 3

4

这实际上并没有编译:您不能将 a King *(表达式的类型new King)分配给 a (表达式Piece的类型*pieces[0])。

但是,要回答您的隐含问题:

Piece *piece = new King(); // fine, no slicing, just assigning a pointer
*piece = Queen();          // oops, slicing - assigning a Queen to a Piece

在您问题的数组中,假设您编写pieces[0] = new King;了 等,您只需存储两个Piece指针,其中一个指向 a King,另一个指向 a Queen

于 2012-03-11T00:25:34.870 回答
1

不会发生切片。您正在执行指针分配,而不是对象分配。

于 2012-03-11T00:21:47.897 回答
0

是的,会发生切片。

每当您尝试将派生类对象放入其任何基类时,总是会发生切片。如果您的派生类添加了一些您的基类不提供的功能,则此切片将变得可见。

请记住,当您没有遵循 OOP 原则时,就会出现这种情况。校长说,

"When you are deriving from any class you should not change the interface. 
The reason for inheritance is moving from generic to specific type, and not
 providing new functionality."

而且,如果你遵循这个原则,那么切片行为可以定义为,

“Moving from specific behaviour to more general behaviour”. 

对指针对象进行切片是临时的,您可以将指针转换回派生类以获得原始行为。切割物体是永久性的。

NOTE:- Slicing always does not happen in case of private inheritance. 
If you try to do so it will result in compilation error.
(For more information on private inheritance:-http://stackoverflow.com/questions/19075517/object-slicing-in-private-inheritance/19083420?noredirect=1#19083420)
于 2013-09-30T16:53:51.707 回答