C++11智能指針之使用shared_ptr實現多態

指針除了管理內存之外,在C++中還有一個重要的功能就是實現多態。

代碼很簡單,還是使用虛函數。與原生指針並沒有什麼區別:

#include <iostream>
#include <memory>
using namespace std;

class parent
{
public:
    parent()
    {
        cout << "parent  constructor" << endl;
    }

    virtual void showinfo()
    {
        cout << "parent info" << endl;
    }

    ~parent()
    {
        cout << "parent  destructor" << endl;
    }
};

class child : public parent
{
public:
    child()
    {
        cout << "child  constructor" << endl;
    }

    virtual void showinfo()
    {
        cout << "child info" << endl;
    }

    ~child()
    {
        cout << "child  destructor" << endl;
    }
};


int main()
{
    shared_ptr<parent> sp = make_shared<child>();
    sp->showinfo();
    return 0;
}

運行程序,輸出爲: 

parent  constructor
child  constructor
child info
child  destructor
parent  destructor



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章