42 lines
720 B
C++
42 lines
720 B
C++
// 向上类型转换
|
|
#include <iostream>
|
|
#include <cstring>
|
|
#include <cstdlib>
|
|
|
|
using namespace std;
|
|
|
|
class Printer
|
|
{
|
|
public:
|
|
void open()
|
|
{
|
|
cout << "打印机正在开机..." << endl;
|
|
}
|
|
};
|
|
|
|
class DellPrinter : public Printer
|
|
{
|
|
void open()
|
|
{
|
|
cout << "Dell打印机..." << endl;
|
|
}
|
|
};
|
|
|
|
class HuaweiPrinter : public Printer
|
|
{
|
|
void open()
|
|
{
|
|
cout << "Huawei打印机..." << endl;
|
|
}
|
|
};
|
|
|
|
int main()
|
|
{
|
|
DellPrinter dellprinter;
|
|
// 多态: 通过父类的引用或指针调用子类对象的成员
|
|
// 子类对象自动向上转换位父类的类型
|
|
Printer &printer = dellprinter;
|
|
printer.open(); // 输出: 打印机正在开机...
|
|
return 0;
|
|
}
|