9.9.6 被指定为new的函数
我们已经知道如何使用override关键字来重写基类中的函数。我们还可以在派生类中将某个函数指定为new,这样可以隐藏基类中签名相同的函数,而且新函数将不参与多态的行为。为了将派生自Box的NewBox类的Volume()函数指定为new,我们可以像下面这样编写代码:
- ref class NewBox : Box // Derived class
- {
- public:
- // New function to calculate the volume of a NewBox object
- virtual double Volume() new
- { return 0.5*m_Length*m_Width*m_Height; }
-
- // Constructor
- NewBox(double lv, double wv, double hv): Box(lv, wv, hv){}
- };
该函数版本隐藏了Box中定义的Volume()函数版本,因此如果我们使用NewBox^类型的句柄调用Volume()函数,则被调用的将是新版本函数。例如:
- NewBox^ newBox = gcnew NewBox(2.0, 3.0,4.0);
- Console::WriteLine(newBox->Volume()); // Output is 12
结果是12,因为新的Volume()函数隐藏了NewBox类从Box继承的多态版本。
新的Volume()函数不是多态函数,因此使用指向基类类型的句柄进行动态调用时,新版本不会被调用。例如:
- Box^ newBox = gcnew NewBox(2.0, 3.0,4.0);
- Console::WriteLine(newBox->Volume()); // Output is 24
NewBox类中仅有的多态Volume()函数是从Box类继承的,因此本例中将调用继承的Volume()函数。