欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

(10)C++智能指针---shared_ptr,dynamic_pointer_cast

程序员文章站 2022-07-12 22:53:56
...
#include <iostream>
#include <thread>
#include <memory> //智能指针所在头文件
using namespace std;
class BaseClass
{
public:
	BaseClass(){}
	~BaseClass(){}
	virtual void print()
	{
		cout << "this is base class" << endl;
	}
protected:
	string _name;
	int _key;



};

class DerivedClass :public BaseClass
{
public:
	DerivedClass() {}
	~DerivedClass(){}
	void print() 
	{
		cout << "this is derived class" << endl;
	}

};
int main()
{
	BaseClass *base = new DerivedClass(); //基类指针可以指向派生类对象

	base->print();  //这里调用print函数是直接调用的派生类的print函数,如果print函数没有加virtual关键字,则会调用基类的print函数
	//DerivedClass *derived = new BaseClass();//这里报错,派生类指针不能指向基类对象

	DerivedClass *de = dynamic_cast<DerivedClass*>(base); //把基类指针所指的对象转换为具体的派生类对象,要能实现这个多态的转换,基类必须要有函数添加关键字virtual
	de->print();

	//智能指针
	cout << "shared pointer" << endl;
	shared_ptr<BaseClass> shared_base = make_shared<DerivedClass>();
	shared_base->print();
	//智能指针基类强转为派生类
	shared_ptr<DerivedClass> shared_de = dynamic_pointer_cast<DerivedClass>(shared_base);
	shared_de->print();

	//由普通指针构造智能指针
	shared_ptr<BaseClass>shared_ba(base);//base 是上面用过的指向派生类的普通指针类型,通过构造函数直接构造智能指针
	shared_ba->print();
	//由智能指针构造普通指针

	BaseClass *common_base;
	common_base = shared_ba.get();
	common_base->print();

	system("pause");

	return 0;
}

 

相关标签: C++学习