面向对象抽象类写动物园
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;
}