純虛函數的作用
在許多情況下,在基類中不能對虛函數給出有意義的實現,而把它聲明為純虛函數,它的實現留給該基類的派生類去做。
1.首先:強調一個概念
定義一個函數為虛函數,不代表函數為不被實現的函數。定義他為虛函數是為了允許用基類的指針來調用子類的這個函數。
定義一個函數為純虛函數,才代表函數沒有被實現。定義他是為了實現一個接口,起到一個規范的作用,規范繼承這個。類的程序員必須實現這個函數。
2.關於實例化一個類:
有純虛函數的類是不可能生成類對象的,如果沒有純虛函數則可以。比如:
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中沒有純虛函數
...
}
3.虛函數在多態中間的使用:
多態一般就是通過指向基類的指針來實現的。
4.有一點你必須明白,就是用父類的指針在運行時刻來調用子類:
例如,有個函數是這樣的:
void animal::fun1(animal *maybedog_maybehorse)
{
maybedog_maybehorse->born();
定義一個函數為虛函數,不代表函數為不被實現的函數。定義他為虛函數是為了允許用基類的指針來調用子類的這個函數。
定義一個函數為純虛函數,才代表函數沒有被實現。定義他是為了實現一個接口,起到一個規范的作用,規范繼承這個。類的程序員必須實現這個函數。
2.關於實例化一個類:
有純虛函數的類是不可能生成類對象的,如果沒有純虛函數則可以。比如:
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中沒有純虛函數
...
}
3.虛函數在多態中間的使用:
多態一般就是通過指向基類的指針來實現的。
4.有一點你必須明白,就是用父類的指針在運行時刻來調用子類:
例如,有個函數是這樣的:
void animal::fun1(animal *maybedog_maybehorse)
{
maybedog_maybehorse->born();
}
參數maybedog_maybehorse在編譯時刻並不知道傳進來的是dog類還是horse類,所以就把它設定為animal類,具體到運行時決定了才決定用那個函數。也就是說用父類指針通過虛函數來決定運行時刻到底是誰而指向誰的函數。
參數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
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()
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;
a.fun1(&b);
}
//output: animal
cout<<"horse";
}
////////////////////main
void main()
{
animal a;
horse b;
a.fun1(&b);
}
//output: animal