C++11智能指针之使用shared_ptr实现多态

来源:互联网 发布:vr照片拍摄软件 编辑:程序博客网 时间:2024/06/10 03:40

指针除了管理内存之外,在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  constructorchild  constructorchild infochild  destructorparent  destructor



0 0
原创粉丝点击