最近使用开发的过程中出现了一个小问题,顺便记录一下原因和方法--虚函数class
/* 【项目1】根据给出的基类Animal和main()函数。 1、根据给出的main()函数和运行结果的提示,计划出相干的各个类,注意观察运行结果,提取出每个类中需要的数据成员,并匹配上需要的成员函数。 2、明显,Animal计划为抽象类更适合,Animal不需要可以实例化,是专门作基类使用的。改革程序,使Animal计划为抽象类,这时main()函数中p = new Animal();将出错,将此行删除。 3、每个Animal的派生类都有一个“名字”数据成员,这一共有的成员完全可以由基类供给改革上面的程序,将这一数据成员作为抽象类Animal数据成员被各派生类使用。 下面是给出的基类Animal和main()函数: */ /* * Copyright (c) 2013, 烟台大学计算机学院 * All rights reserved. * 文件名称:test.cpp * 作者:邱学伟 * 完成日期:2013 年 5 月 31 日 * 版本号:v1.0 * 输入描述:无 * 问题描述: * 程序输出: * 问题分析: * 算法计划:略 */ #include <iostream> using namespace std; class Animal { public: virtual void cry() { cout<<"不知哪类动物,让我如何学叫?"<<endl; } }; class Mouse:public Animal { public: Mouse(string n,char s); void cry(); private: string name; char sex; }; Mouse::Mouse(string n,char s) { name=n; sex=s; } void Mouse::cry() { if(sex=='m') cout<<"我叫"<<name<<",我是一只男老鼠,我的啼声是”吱吱吱“"<<endl; if(sex=='f') cout<<"我叫"<<name<<",我是一只女老鼠,我的啼声是”吱吱吱“"<<endl; } class Cat:public Animal { public: Cat(string n,char s); void cry(); private: string name; char sex; }; Cat::Cat(string n,char s):name(n),sex(s) {} void Cat::cry() { if(sex=='m') cout<<"我叫"<<name<<",我是一只公猫,我的啼声是”喵喵喵“"<<endl; if(sex=='f') cout<<"我叫"<<name<<",我是一只母猫,我的啼声是”喵喵喵“"<<endl; } class Dog:public Animal { public: Dog(string n); void cry(); private: string name; }; Dog::Dog(string n):name(n) {} void Dog::cry() { cout<<"我是一只狗,我的啼声是“汪汪汪”"<<endl; } class Giraffe:public Animal { public: Giraffe(string n,char s); void cry(); private: string name; char sex; }; Giraffe::Giraffe(string n,char s):name(n),sex(s) {} void Giraffe::cry() { cout<<"我叫"<<name<<",我是一只长颈鹿,我的脖子太长,发不出声音来"<<endl; } int main( ) { Animal *p; p = new Animal(); p->cry(); Mouse m1("Jerry",'m'); p=&m1; p->cry(); Mouse m2("Jemmy",'f'); p=&m2; p->cry(); Cat c1("Tom",'f'); p=&c1; p->cry(); Dog d1("Droopy"); p=&d1; p->cry(); Giraffe g1("Gill",'m'); p=&g1; p->cry(); return 0; }
文章结束给大家分享下程序员的一些笑话语录: 面试官:熟悉哪种语言
应聘者:JAVA
面试官:知道什么叫类么
应聘者:我这人实在,工作努力,不知道什么叫累
面试官:知道什么是包?
应聘者:我这人实在 平常不带包 也不用公司准备了
面试官:知道什么是接口吗?
应聘者:我这个人工作认真。从来不找借口偷懒
面试官:知道什么是继承么
应聘者:我是孤儿没什么可以继承的
面试官:知道什么叫对象么?
应聘者:知道,不过我工作努力,上进心强,暂时还没有打算找对象。
面试官:知道多态么?
应聘者:知道,我很保守的。我认为让心爱的女人为了自已一时的快乐去堕胎是不道德的行为!请问这和C#有什么关系??
---------------------------------
原创文章 By
虚函数和class
---------------------------------