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; }