课时33示例--为多态基类声明虚析构函数
微软校园招聘笔试题
#include <iostream> class Base { public: char Value() { return 'A'; } virtual char VirtualValue() { return 'X'; } }; class Derived :public Base { public: char Value() { return 'U'; } }; class VirtualDerived :virtual public Base { public: char Value() { return 'Z'; } char VirtualValue() { return 'V'; } }; int main() { Base *p1 = new Derived(); Base *p2 = new VirtualDerived(); std::cout << p1->Value() << " " << p1->VirtualValue() << " " << p2->Value() << " " << p2->VirtualValue() << std::endl; system("pause"); return 0; }
A X A V
请按任意键继续. . .
课时34案例讲解--简单工厂
案例讲解
简单工厂
案例介绍
模拟种植园管理程序
种植园里种苹果、葡萄等水果
案例设计
使用简单工厂模式实现开闭原则
#include <iostream> enum { APPLE = 0, GRAPE = 1 }; class Fruit { public: virtual ~Fruit() = 0; virtual void plant() = 0; virtual void grow() = 0; virtual void harvest() = 0; }; class Apple :public Fruit { public: Apple(); ~Apple(); virtual void plant(); virtual void grow(); virtual void harvest(); }; class Grape :public Fruit { public: Grape(); ~Grape(); virtual void plant(); virtual void grow(); virtual void harvest(); }; class Gardener { public: Gardener(); ~Gardener(); Fruit* getFruit(int type); private: Apple* apple; Grape* grape; }; Fruit::~Fruit() { } Apple::Apple() { std::cout << "apple constructing" << std::endl; } Apple::~Apple() { std::cout << "apple destructing" << std::endl; } void Apple::plant() { std::cout << "apple plant" << std::endl; } void Apple::grow() { std::cout << "apple grow" << std::endl; } void Apple::harvest() { std::cout << "apple harvest" << std::endl; } Grape::Grape() { std::cout << "grape constructing" << std::endl; } Grape::~Grape() { std::cout << "grape destructing" << std::endl; } void Grape::plant() { std::cout << "grape plant" << std::endl; } void Grape::grow() { std::cout << "grape grow" << std::endl; } void Grape::harvest() { std::cout << "grape harvest" << std::endl; } Gardener::Gardener() { apple = nullptr; grape = nullptr; } Gardener::~Gardener() { } Fruit* Gardener::getFruit(int type) { Fruit *fruit = nullptr; if (APPLE == type) { if (nullptr == apple) { apple = new Apple(); } fruit = apple; } else if (GRAPE == type) { if (nullptr == grape) { grape = new Grape(); } fruit = grape; } else { } return fruit; } int main() { Gardener tom; Fruit* fruit = tom.getFruit(APPLE); fruit->plant(); fruit->grow(); fruit->harvest(); system("pause"); return 0; }