这是合乎逻辑的。每个派生的对象都是基础对象,因此上传是自动的。但是每个基础对象都不是派生的,因此你需要明确地施放它。
看到这个简单的例子:
struct Fruit {};
struct Apple : Fruit {};
Apple apple;
Fruit fruit;
fruit = apple; //ok - automatic - since apple is fruit (see "object slicing")
apple = fruit; //error - not automatic - since fruit is necessarily apple!
请参阅错误和行号:
http://ideone.com/JnLc2
但是,如果你重载以下列方式operator=
,
struct Apple : Fruit
{
Apple & operator = (const Fruit &);
};
然后显式转换不需要。你可以写
apple = fruit; //alright - assignment (not construction)
看到这个:http://ideone.com/IGbFI
现在,如果你补充一点:
struct Apple : Fruit
{
Apple(const Fruit &);
};
,那么你可以写
Apple apple = fruit ; //ok - construction (not assignment)
看到这个:http://ideone.com/muQc0
请注意,在第一个赋值“b = d”中,该对象将被*切片*以将其转换为“B”实例。这可能不是你通常想要或期望的。 – Thomas 2011-03-05 18:26:23