码迷,mamicode.com
首页 > 编程语言 > 详细

c++-zoo动物园

时间:2019-12-22 14:33:28      阅读:376      评论:0      收藏:0      [点我收藏+]

标签:end   pre   name   let   names   继承   Once   stream   virtual   

面向对象抽象类写动物园

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 << "1·?aê??Tá?£? 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;
}

c++-zoo动物园

标签:end   pre   name   let   names   继承   Once   stream   virtual   

原文地址:https://www.cnblogs.com/ygjzs/p/12079672.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!