C++虚函数与纯虚函数

来源:互联网 发布:淘宝客服转化率怎么算 编辑:程序博客网 时间:2024/06/10 14:33

注:本人C++初学者,在虚函数与纯虚函数这块,网上看到这篇论述确为良品,遂转载以示感动。

首先:强调一个概念

定义一个函数为虚函数,不代表函数为不被实现的函数
    定义他为虚函数是为了允许用基类的指针来调用子类的这个函数
定义一个函数为纯虚函数,才代表函数没有被实现
    定义他是为了实现一个接口,起到一个规范的作用,规范继承这个
    类的程序员必须实现这个函数。

对继承的影响:
    普通的类(没有虚函数,纯虚函数)就可以被继承,而且工作的相当好

关于这个问题有以下疑问:
    纯虚函数难道就是为了实现接口?接口存在的意义?
我实在弄不懂,我干嘛要预先定义好?未来的事情本难料
就等有一天我的类中需要使用某个函数,再添加一个函数
不就可以吗?

关于实例化一个类:
有纯虚函数的类是不可能生成类对象的,如果没有纯虚函数则可以。比如:
class CA{public:    virtual void fun() = 0;  // 说明fun函数为纯虚函数    virtual void fun1();};class CB{public:   virtual void fun();   virtual void fun1();};// CA,CB类的实现...void main(){    CA a;   // 不允许,因为类CA中有纯虚函数    CB b;   // 可以,因为类CB中没有纯虚函数    ...}
---------------------------------------------------------------
虚函数在多态中间的使用:
虚函数主要实现多态机制,避免二义性问题。 
多态一般就是通过指向基类的指针来实现的。

dog mydogwangwang;mydogwangwang.born();

一定是返回“dog”
那么
horse myhorsepipi;myhorsepipi.born();
一定是返回“horse”
也是多态呀? 
/////////////////////////////////////////////////
有一点你必须明白,就是用父类的指针在运行时刻来调用子类:
例如,有个函数是这样的:
void animal::fun1(animal *maybedog_maybehorse){  maybedog_maybehorse->born();}
参数maybedog_maybehorse在编译时刻并不知道传进来的是dog类还是horse类,所以就把它设定为animal类,具体到运行时决定了才决定用那个函数。
也就是说用父类指针通过虚函数来决定运行时刻到底是谁而指向谁的函数。
//////////////////////////////////////////////////////////////////////用虚函数#include <iostream.h>class animal{public:animal();~animal();void fun1(animal *maybedog_maybehorse);virtual void born(); //虚函数解决调用函数二义性。};void animal::fun1(animal *maybedog_maybehorse){  maybedog_maybehorse->born();}animal::animal(){}animal::~animal(){}void animal::born(){cout<< "animal";}class dog: public animal{public:dog();~dog();virtual void born();};dog::dog(){}dog::~dog(){}void dog::born(){cout<<"dog";}class horse:public animal{public:horse();~horse();virtual void born();};horse::horse(){}horse::~horse(){}void horse::born(){cout<<"horse";}void main(){animal a;dog b;horse c;a.fun1(&c);}//output: horse

/////////////////////////////////////////////////////////////////
//不用虚函数
#include <iostream.h>class animal{public:animal();~animal();void fun1(animal *maybedog_maybehorse); void born();};void animal::fun1(animal *maybedog_maybehorse){  maybedog_maybehorse->born();}animal::animal(){}animal::~animal(){}void animal::born(){cout<< "animal";}class dog: public animal{public:dog();~dog(); void born();};dog::dog(){}dog::~dog(){}void dog::born(){cout<<"dog";}class horse:public animal{public:horse();~horse(); void born();};horse::horse(){}horse::~horse(){}void horse::born(){cout<<"horse";}void main(){animal a;dog b;horse c;a.fun1(&c);}output: animal
---------------------------------------------------------------
有纯虚函数的类是抽象类,不能生成对象,只能派生。他派生的类的纯虚函数没有被改写,那么,它的派生类还是个抽象类。
---------------------------------------------------------------
定义纯虚函数就是为了让基类不可实例化化,
因为实例化这样的抽象数据结构本身并没有意义.
或者给出实现也没有意义
原创粉丝点击