指針除了管理內存之外,在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