智能指针下的多态

想不到,智能指针也可以实现运行多态,大笑。下面展示了个小例子。

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

class P
{
public:
	P()
	{	cout<<"P construction"<<endl;	}
	virtual void f(int t)
	{	cout <<"P!!"<<",t="<<t<<endl;	}
	~P()
	{	cout<<"P destroy"<<endl;	}
};
class C1 :public P
{
public:
	C1()
	{	cout<<"C1 construction"<<endl;	}
	void f(int t)
	{	cout <<"C1!!"<<",t="<<t<<endl;	}
	~C1()
	{	cout<<"C1 destroy"<<endl;	}
};
class C2 : public P
{
public:
	C2()
	{	cout<<"C2 construction"<<endl;	}
	 void f(int t)
	{	cout <<"C2!!"<<",t="<<t<<endl;	}
	 ~C2()
	{	cout<<"C2 destroy"<<endl;	}
};
void test1(int t)
{
	这里需要预先生成所有的字对象,这是不优美的
	C1 myc1;
	C2 myc2;
	
	P * myp = NULL;
	cout<<"test1 start..."<<endl;
	if(t>5)
	{	myp = &myc1;	}
	else
	{	myp = &myc2;	}
	myp->f(t);
}
void test2(int t)
{
	///这里按需new子对象,切无须担心内存释放
	std::tr1::shared_ptr<P> myPtr;
	cout<<"test2 start..."<<endl;
	if(t>5)
	{	
		//下面这种方式会生成临时一个智能指针,不是很安全
		myPtr = std::tr1::shared_ptr<P>(new C1);
	}
	else
	{	
		///给每个智能指针都起一个名字会安全得多
		std::tr1::shared_ptr<P> C2Ptr(new C2);
		myPtr = C2Ptr;
	}
	myPtr->f(t);//
}
int main()
{
	test1(2);
	test1(20);
	cout<<"====================="<<endl;
	test2(2);
	test2(20);
}
结果如下:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值