animal.hios
#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.h函数
#pragma once #include "Animal.h" class Dog : public Animal { public: Dog(); ~Dog(); virtual void voice(); };
dog.cppspa
#include "Dog.h" Dog::Dog() { cout << "Dog().." << endl; } Dog::~Dog() { cout << "~Dog().." << endl; } void Dog::voice() { cout << "¹·¿ªÊ¼¿ÞÁË£¬ 555" << endl; }
cat.hcode
#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.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; }