Posted on 2010-11-12 20:07
kongkongzi 阅读(368)
评论(0) 编辑 收藏 引用 所属分类:
c++ programming
// base.h
#include <iostream>
class Base
{
public:
Base() { std::cout << "Base::Base" << std::endl; }
~Base() { std::cout << "Base::~Base" << std::endl; }
virtual void Init() { std::cout << "Base::Init" << std::endl; }
virtual void Final() { std::cout << "Base::Final" << std::endl; }
virtual void Print() { std::cout << "Base::Print" << std::endl; }
void Call() { Print(); }
};
// derived.h
#include "base.h"
class Derived : public Base
{
public:
Derived() { std::cout << "Derived::Derived" << std::endl; }
~Derived() { std::cout << "Derived::~Derived" << std::endl; }
virtual void Init() { std::cout << "Derived::Init" << std::endl; }
virtual void Final() { std::cout << "Derived::Final" << std::endl; }
virtual void Print() { std::cout << "Derived::Print" << std::endl; }
};
// main.cpp
#include <derived.h>
int main(void)
{
Base *pD = new Derived();
pD->Init();
pD->Call();
pD->Final();
delete pD;
pD = NULL;
return 0;
}
Results:
Base::Base
Derived::Derived
Derived::Init
Derived::Print
Derived::Final
Base::~Base
若在Base的构造函数里调用Call(),那么将打印:“Base::Print
“,这是因为Base在构造的时候,Derived本身还没有构造好。