C++学习笔记4 String类的实现,三大函数

//简易版string类  String
#ifndef _MYSTRING_
#define _MYSTRING_

class String
{
	public:
		String(const char* cstr = 0);
		String(const String& str);
		String& operator = (const String& str);
		~String();
		char* get_c_str() const {  return my_data;}
	private:
		char* my_data;
};

};

#endif

int main()
{
	String s1();
	String s2("hello");
	String s3(s1);                       //拷贝构造
	s3 = s2;		            //拷贝复制







//简易版string类  String
#ifndef _MYSTRING_
#define _MYSTRING_

class String
{
	public:
		String(const char* cstr = 0);           //构造函数                                     
		String(const String& str);                //拷贝构造,因为它接受的是和自己一样的东西
		String& operator = (const String& str);         //拷贝赋值
		~String();                                         //析构函数:在String类变量死亡时调用析构函数
		char* get_c_str() const {  return my_data;}     //普通成员函数
	private:
		char* my_data;
};

};

inline
String::String(const char* cstr = 0)
{
	if(cstr){
		my_data = new char[strlen(cstr)+1];
		strcpy(my_data, cstr);
	}
	else{
		my_data = new char[1];
		*m_data = '\0';
	}
}

inline
String::~String()                    //构造动态分配(new)了内存,在这里必须收回内存,否则就是内存泄漏
{
	delete[] m_data;
}












#endif

int main()
{
	String s1();
	String s2("hello");
	String s3(s1);                       //拷贝构造
	s3 = s2;		            //拷贝复制







class with pointer members 必须有 copy ctor(拷贝构造) 和 copy op=(拷贝赋值) 
inline 
String::String(const char* cstr = 0)
{
	if(cstr){
		m_data = new char[strlen(cstr)+1];
		strcpy(m_data, cstr);
	}
	else{
		m_data = new char[1];
		*m_data = '\0';
	}
}

inline
String::~String()
{
	delete[] m_data;
}


ostream& operator << (ostream& os, const String& str)
{
	os << str.get_c_str();
	return os;
}

{
	String s1("hello ");
	cout << s1;
}











 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值