时间:2021-07-18 08:26:22 | 栏目:C代码 | 点击:次
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,就会走虚函数的流程。