您的位置:首页 > 编程语言 > C语言/C++

effective c++ 为多态基类声明virtual析构函数

2015-09-10 22:39 591 查看
C++的多态性

class TextBlock
{
public:
    virtual void foo()
    {
        cout << "TextBlock" << endl;
    }
};
class Text : public TextBlock
{
public:
    void foo()
    {
        cout << "Text" << endl;
    }
};
int main()
{
    TextBlock *a = new TextBlock;
    TextBlock *b = new Text;
    Text *c = new Text;
    a -> foo();
    //TextBlock
    b -> foo();
    //Text -> polymorphically
    c -> foo();
    //Text
}


当derived class 对象经由一个base class指针被删除,而该base class带着一个non-virtual析构函数,其结果未有定义—–实际执行通常是derived成分没有被销毁

任何class只要带virtual函数都几乎确定应该也有一个virtual 析构函数

class TextBlock
{
public:
    virtual void foo()
    {
        cout << "TextBlock" << endl;
    }
    virtual ~TextBlock(){}
};
class Text : public TextBlock
{
public:
    void foo()
    {
        cout << "Text" << endl;
    }
};
int main()
{
    TextBlock *b = new Text;
    b -> foo();
    delete b;
}


class TextBlock : public string
{
    //馊主意,string有个non-virtual析构函数
};
int main()
{
    TextBlock * p1 = new TextBlock();
    string * p2 = p1;
    delete p2; ///未定义!
}


为你希望成为抽象的那个class声明一个pure virtual析构函数

class TextBlock
{
public:
    virtual ~TextBlock() = 0;
};
class Text : public TextBlock
{

};
TextBlock::~TextBlock(){}
//如果没有定义,会编译错误
//编译器会在Text的析构函数中创建一个~TextBlock()的调用动作
int main()
{
    TextBlock * p = new Text;
    delete p;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: