关于虚函数(多态)与继承的一道搜狗笔试题

#include<iostream>
using namespace std;
/*
  Name: 
  Copyright: 
  Author: 
  Date: 25/03/13 09:12
  Description: 虚函数的作用是多态的应用,这样用子类去new一个父类的对象将调用子类的方法 
*/

class Base{
public:
       Base(int j):i(j){}
       virtual ~Base(){printf("Base del\n");} //此处若不加 virtual,那么将不会调用基类析构 
       void func1(){printf("Base func1\n");i*=10;func2();}
       int getValue(){return i;}
protected:
       virtual void func2(){printf("Base func2\n");i++;}
protected:
       int i;
};

class Child :public Base{
public:
       ~Child(){printf("child del\n");} 
       Child(int j):Base(j){}
       void func1(){printf("child func1\n");i*=100;func2();}
protected:
       void func2(){printf("child func2\n");i+=2;}
};

int main()
{
    Base *pb=new Child(1); //多态 
    pb->func1();
    cout<<pb->getValue()<<endl;
    delete pb;
    system("pause");
}

输出结果:
Base func1
child func2
12
child del
Base del

 
posted @ 2013-03-25 09:16  一枚程序员  阅读(439)  评论(0编辑  收藏  举报