- 多态的好处:扩展性强、组织结构清晰、代码可读性强
示例
#include<iostream>
using namespace std;
class make_drink {
public:
virtual void boil() = 0;
virtual void brew() = 0;
virtual void inCup() = 0;
virtual void putSomething() = 0;
void makedrink() {
boil();
brew();
inCup();
putSomething();
}
// 纯虚析构函数
virtual ~make_drink() = 0;
// 虚析构函数
/*virtual ~make_drink() {
cout << "喝完了" << endl;
}*/
};
// 纯虚析构函数
make_drink::~make_drink(){
cout << "喝完了" << endl;
}
class coffee:public make_drink {
public:
void boil() {
cout << "煮怡宝" << endl;
};
void brew() {
cout << "冲咖啡" << endl;
};
void inCup() {
cout << "倒进杯子里" << endl;
};
void putSomething() {
cout << "加牛奶,加糖" << endl;
};
~coffee(){
cout << "咖啡做完了" << endl;
}
};
class tea:public make_drink {
private:
public:
void boil() {
cout << "煮农夫山泉" << endl;
};
void brew() {
cout << "泡茶" << endl;
};
void inCup() {
cout << "倒进杯子里" << endl;
};
void putSomething() {
cout << "加柠檬,加糖" << endl;
};
~tea() {
cout << "茶做完了" << endl;
}
};
void test() {
make_drink *mc=new coffee();
mc->makedrink();
delete mc;
cout << "--------------" << endl;
make_drink *mt=new tea();
mt->makedrink();
delete mt;
}
int main() {
test();
system("pause");
return EXIT_SUCCESS;
}
运行结果
煮怡宝
冲咖啡
倒进杯子里
加牛奶,加糖
咖啡做完了
喝完了
--------------
煮农夫山泉
冲茶
倒进杯子里
加柠檬,加糖
茶做完了
喝完了
请按任意键继续. . .