C++使用shared_ptr(智能指针) 实现多态调用

#include <iostream>
#include <vector>

using namespace std;
using LL = long long int;

#define debug(x) cout<<#x<<": "<<(x)<<endl;
#define deOut(x) cout<<#x<<": "<<(x)<<" ";
#define de15lf(x) {cout<<#x<<": "; printf("%.15lf\n",x);}

using Str = string;

template<typename T>
using Vec = vector<T>;

class Shape
{
public:
	Str name;
	Shape(Str name) {
		this->name = name;
		cout << name << " is create" << endl;
	}
	~Shape() {
		cout << name << " is deleted" << endl;
	}

	virtual bool disp() {
		cout << "this is "<< name << endl;
		return true;
	}

};

class Rec: public Shape
{
public:
	Rec(Str name) :Shape(name) {}
	~Rec() {
		cout << "Rec is deleted" << endl;
	}

	bool disp() {
		cout << "Rec this is " << name << endl;
		return true;
	}
};

class Cycyle: public Shape
{
public:
	Cycyle(Str name) :Shape(name) {}
	~Cycyle() {
		cout << "Cycyle is deleted" << endl;
	}

	bool disp() {
		cout << "Cycyle this is " << name << endl;
		return true;
	}

};

int main(int argc, char* argv[] )
{
	using ssptr = shared_ptr<Shape>;
	Vec<ssptr> ve;

	ssptr s1 = ssptr(new Rec("r0"));

	ve.push_back(s1);
	s1->disp();
	ve[0]->disp();

	ve.push_back(ssptr(new Rec("r1")));
	ve.push_back(ssptr(new Rec("r2")));
	ve.push_back(ssptr(new Cycyle("c1")));
	ve.push_back(ssptr(new Cycyle("c2")));

	for (int i = 0; i < ve.size(); i++) {
		ve[i]->disp();
	}
	return 0;
}

在这里插入图片描述

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页