万丈高楼平地起——设计虚类请注意

类别:编程语言 点击:0 评论:0 推荐:

在定义虚类尤其是纯虚类时,请注意将虚类的析构函数设计为虚拟函数,否则其子类实例的内存释放操作将不正常。如:

Packets.h
#include
class CPacket
{
public:
    virtual ~CPacket() {};

    virtual void Initialize() = 0;
    ...
};

class CDeliverPacket: public CPacket
{
public:
    virtual ~CDeliverPacket() {std::cout << "CDeliverPacket Destroy" << std::endl;};

    virtual void Initialize() {std::cout << "CDeliverPacket Initialize" << std::endl;};
};

main.cpp
#include "Packets.h"

int main(int argc, char **argv)
{
    CPacket *pPacket = new CDeliverPacket();
    pPacket->Initialize();
    delete pPacket;
}

输出:
    CDeliverPacket Initialize
    CDeliverPacket Destroy

蓝色的代码看似无用,但如果没有那一行将不会调用显示CDeliverPacket Destroy等代码。

本文地址:http://com.8s8s.com/it/it27539.htm