首先:強調一個概念
定義一個函數爲虛函數,不代表函數爲不被實現的函數
定義他爲虛函數是爲了允許用基類的指針來調用子類的這個函數
定義一個函數爲純虛函數,才代表函數沒有被實現
定義他是爲了實現一個接口,起到一個規範的作用,規範繼承這個
類的程序員必須實現這個函數。
關於實例化一個類:
有純虛函數的類是不可能生成類對象的,如果沒有純虛函數則可以。比如:
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
---------------------------------------------------------------
有純虛函數的類是抽象類,不能生成對象,只能派生。他派生的類的純虛函數沒有被改寫,那麼,它的派生類還是個抽象類。