对象作为它自己的类或作为它的基类的对象来使用
还能通过基类的地址操作它
取一个对象的地址 指针或引用,并将其作为基类的地址来处理,这称为向上
类型转换 upcasting,因为继承树的绘制方式是以基类为顶点的
//: C14:Instrument.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Inheritance & upcasting
enum note { middleC, Csharp, Cflat }; // Etc.
class Instrument {
public:
void play(note) const {}
};
// Wind objects are Instruments
// because they have the same interface:
class Wind : public Instrument {};
void tune(Instrument& i) {
// ...
i.play(middleC);
}
int main() {
Wind flute;
tune(flute); // Upcasting
} ///:~
函数tune() 通过引用 接受一个Instrument,但也不拒绝任何从Instrument
派生的类
在mian()中,可以看到,无须类型转换,就能将Wind对象传给tune()
处理指针时采用相同的参数,唯一不同的是用户必须显式地取对象的地址传给函数