码迷,mamicode.com
首页 > 编程语言 > 详细

【c++】浅拷贝成功__count解决

时间:2015-06-05 22:49:07      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:浅拷贝

#include <iostream>
#include <string.h>
using namespace std;

class String
{
public:
	String(const char *str = " ")
	{
		m_data = new char[strlen(str) + 1];
		strcpy(m_data, str);
		count++;
	}
	String(const String &s)
	{
		m_data = s.m_data;
		count++;
	}
	~String()
	{
		//当指针释放到只剩一个的时候,再释放就不会崩溃了
		if (--count == 1)
		{
			delete[]m_data;
		}
	}
public:
	void print()
	{
		cout << m_data << endl;
	}
private:
	char *m_data;
	static int count;//定义一个计数器,表示当前空间上有多少个指针指向
};

int String::count = 0;

int main()
{
	String s("hello");
	s.print();
	String s1 = s;
	s1.print();
	return 0;
}



技术分享

【c++】浅拷贝成功__count解决

标签:浅拷贝

原文地址:http://blog.csdn.net/zhaoyaqian552/article/details/46380387

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!