假设我有一个指向抽象类的指针数组:
Piece *pieces[2]; // where piece is an abstract class
我有两个扩展名为Piece
King
和Queen
的类。我将King
分配到pieces
和Queen
中的某个位置到另一个位置:
pieces[0] = new King();
pieces[1] = new Queen();
如果我没有重载赋值运算符,是否会发生切片?或者pieces[0]
是King
的实例,而pieces[1]
是Queen
的实例?该数组中发生了什么(如果这是C ++)?
编辑:查看问题代码here的完整示例。
答案 0 :(得分:4)
这实际上并没有编译:您无法将King *
(表达式new King
的类型)分配给Piece
(表达式{{1}的类型})。
回答你的隐含问题:
*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
和其中一个指向King
。
答案 1 :(得分:1)
不会发生切片。你正在做指针赋值,而不是对象赋值。
答案 2 :(得分: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)