C++编程思想 第1卷 第15章 多态性和虚函数 向上类型转换

对象作为它自己的类或作为它的基类的对象来使用
还能通过基类的地址操作它
取一个对象的地址 指针或引用,并将其作为基类的地址来处理,这称为向上
类型转换 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()

处理指针时采用相同的参数,唯一不同的是用户必须显式地取对象的地址传给函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值