代碼如下:
#include<iostream>
class base{
public:
base()
{
std::cout<<std::endl;
std::cout<<"base constructor"<<std::endl;
func1();
std::cout<<std::endl;
}
virtual ~base()
{
std::cout<<std::endl;
std::cout<<"base distructor"<<std::endl;
func1();
std::cout<<std::endl;
}
virtual void func1()
{
std::cout<<"base virtural func1"<<std::endl;
}
void func2()
{
std::cout<<"base member func2"<<std::endl;
func1();
std::cout<<std::endl;
}
};
class derived:public base{
public:
derived()
{
std::cout<<std::endl;
std::cout<<"derived constructor"<<std::endl;
func1();
std::cout<<std::endl;
}
virtual ~derived()
{
std::cout<<std::endl;
std::cout<<"derived distructor"<<std::endl;
func1();
std::cout<<std::endl;
}
virtual void func1()
{
std::cout<<"derived virtual func1"<<std::endl;
}
};
int main()
{
base *point = new derived();
point->func2();
delete point;
return 0;
}
會有這樣的輸出
即使func1是虛函數,在base類和derived的構造函數和析構函數裡面,都是調用自己類裡面的func1。
而在普通成員函數func2調用func1,就會走虛函數的流程。