虚函数和纯虚函数区别:
虚函数必须是基类的非静态成员函数,其访问权限可以是protected或public,在基类的类定义中定义虚函数的一般形式:
virtual 函数返回值类型虚函数名〔形参表〕
{ 函数体 }
一样点:虚函数和纯虚函数都是为了实现多态机制的,目的是给派生类修改基类行为的时机。
不同点:虚函数可以在基类中定义默认的行为,假设派生类没有对其行为进展覆盖,那么基类的默认行为生效,假设派生类对其覆盖,那么会自动调用派生类的行为;纯虚函数不在基类中提供默认的行为,只是提供一个接口声明。
因此,纯虚函数只是声明接口,不提供行为实现。包含了纯虚函数的类被称为虚基类,无法声明实例。纯虚类生来就是需要被继承并修改其行为的。
观点一:
虚函数在子类里面也可以不重载的;但纯虚必须在子类去实现,这就像Java的接口一样。通常我们把很多函数加上virtual,是一个好的习惯,虽然牺牲了一些性能,但是增加了面向对象的多态性,因为你很难意料到父类里面的这个函数不在子类里面不去修改它的实现观点二:
带纯虚函数的类叫虚基类,这种基类不能直接生成对象,而只有被继承,并重写其虚函数后,才能使用。这样的类也叫抽象类。虚函数是为了继承接口和默认行为
观点三:
类里声明为虚函数的话,这个函数是实现的,哪怕是空实现,它的作用就是为了能让这个函数在它的子类里面可以被重载,这样的话,这样编译器就可以使用后期绑定来到达多态了。纯虚函数只是一个接口,是个函数的声明而已,它要留到子类里去实现。
观点四:
虚函数的类用于CMS的“实作继承〞,继承接口的同时也继承了父类的实现。当然我们也可以完成自己的实现。纯虚函数的类用于“介面继承〞,主要用于通信协议方面。关注的是接口的统一性,实现由子类完成。一般来说,介面类中只有纯虚函数的。
1.首先:强调一个概念
定义一个函数为虚函数,不代表函数为不被实现的函数。定义他为虚函数是为了允许用基类的指针来调用子类的这个函数。
定义一个函数为纯虚函数,才代表函数没有被实现。定义他是为了实现一个接口,起到一个标准的作用,标准继承这个。类的程序员必须实现这个函数。
2.关于实例化一个类:
有纯虚函数的类是不可能生成类对象的,假设没有纯虚函数那么可以。比方:
class CA
{
public:
virtual void fun() = 0;  //在基类中实现纯虚函数的方法是在函数原型后加“=0〞virtual void funtion1()=0
virtual void fun1();
};
class CB
{
public:
virtual void fun();
virtual void fun1();
};
// CA,CB类的实现
...
void main()
{
CA a;  // 不允许,因为类CA中有纯虚函数
CB b;  // 可以,因为类CB中没有纯虚函数
...
}
3.虚函数在多态中间的使用:
多态一般就是通过指向基类的指针来实现的。
4.有一点你必须明白,就是用父类的指针在运行时刻来调用子类:
例如,有个函数是这样的:
void animal::fun1(animal *maybedog_maybehorse)
{多态性与虚函数
maybedog_maybehorse->born();
}
参数maybedog_maybehorse在编译时刻并不知道传进来的是dog类还是horse类,所以就把它设定为animal类,详细到运行时决定了才决定用那个函数。也就是说用父类指针通过虚函数来决定运行时刻到底是谁而指向谁的函数。
5.用虚函数
#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";
}
/
//////////////////////horse
class horse:public animal
{
public:
horse();
~horse();
virtual void born();
};
horse::horse() { }
horse::~horse() { }
void horse::born()
{
cout<<"horse";
}
///////////////////////main
void main()
{
animal a;
horse b;
a.fun1(&b);
}
//output: horse
6.不用虚函数
#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";
}
////////////////////////horse
class horse:public animal
{
public:
horse();
~horse();
void born();
};
horse::horse() { }
horse::~horse() { }
void horse::born()
{
cout<<"horse";
}
/
///////////////////main
void main()
{
animal a;
horse b;