虚函数被类的构造析构函数和成员函数调用虚函数的执行过程
#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,就会走虚函数的流程。
上一篇:C语言数据结构实现链表去重的实例
栏 目:C代码
本文标题:虚函数被类的构造析构函数和成员函数调用虚函数的执行过程
本文地址:http://www.codeinn.net/misctech/158801.html