c++-zoo动物园
程序员文章站
2022-08-02 21:56:30
面向对象抽象类写动物园 animal animal.h animal.cpp dog dog.h dog.cpp ......
面向对象抽象类写动物园
animal
animal.h
#pragma once #define _crt_secure_no_warnings #include <iostream> using namespace std; class animal { public: //纯虚函数,让子类继承并且实现 virtual void voice() = 0; animal(); virtual ~animal(); }; //架构函数 //让动物叫 void letanimalcry(animal *animal);
animal.cpp
#include "animal.h" animal::animal() { cout << "animal().." << endl; } animal::~animal() { cout << "~animal()..." << endl; } void letanimalcry(animal *animal) { animal->voice(); if (animal != null) { delete animal; } }
dog
dog.h
#pragma once #include "animal.h" class dog : public animal { public: dog(); ~dog(); virtual void voice(); };
dog.cpp
#include "dog.h" dog::dog() { cout << "dog().." << endl; } dog::~dog() { cout << "~dog().." << endl; } void dog::voice() { cout << "¹·¿ªê¼¿þá룬 555" << endl; }
cat
cat.h
#pragma once #include "animal.h" class cat : public animal { public: cat(); ~cat(); virtual void voice(); };
cat.cpp
#include "cat.h" cat::cat() { cout << "cat().." << endl; } cat::~cat() { cout << "~cat().." << endl; } void cat::voice() { cout << "小猫开始哭了,66666" << endl; }
main
main.cpp
#define _crt_secure_no_warnings #include <iostream> #include "animal.h" #include "dog.h" #include "cat.h" using namespace std; int main(void) { letanimalcry(new dog); letanimalcry(new cat); #if 0 animal *dog = new dog; letanimalcry(dog); delete dog; #endif return 0; }