65,210
社区成员
发帖
与我相关
我的任务
分享#include <iostream>
#include <string>
class CBase
{
public:
CBase()
{
vfunc("CBase Constructor");
}
~CBase()
{
vfunc("CBase Destructor");
}
virtual void vfunc(std::string str)
{
std::cout<<"CBase::vfunc:"<<str<<std::endl;
}
};
class CDerived: public CBase
{
public:
CDerived()
{
vfunc("CDerived Constructor");
}
~CDerived()
{
vfunc("CDerived Destructor");
}
virtual void vfunc(std::string str)
{
std::cout<<"CDerived::vfunc:"<<str<<std::endl;
}
};
int main(int argc, char * argv[])
{
CDerived d1;
return 0;
}
#include <iostream>
#include <string>
class CBase
{
public:
CBase()
{
vfunc("CBase Constructor");
}
virtual ~CBase() //增加virtual,如果不增加virtual,delete 基类指针时不会调用派生类虚构函数
{
vfunc("CBase Destructor");
}
virtual void vfunc(std::string str)
{
std::cout<<"CBase::vfunc:"<<str<<std::endl;
}
};
class CDerived: public CBase
{
public:
CDerived()
{
vfunc("CDerived Constructor");
}
~CDerived()
{
vfunc("CDerived Destructor");
}
virtual void vfunc(std::string str)
{
std::cout<<"CDerived::vfunc:"<<str<<std::endl;
}
};
int main()
{
CBase *p = new CDerived(); //先调用基类构造函数,再调用派生类构造函数
//CDerived d1;
p->vfunc("test"); //多态,调用派生类的vfunc()
delete (CBase *) p; // 先调用派生类虚构函数,再调用基类虚构函数;
return 0;
}