String

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


class String
{
public:
	String(const char *str = NULL);
	String(const String &another);
	~String();
	String &operator = (const String *rhs);
	friend ostream&operator <<(ostream &os, const String&str);
protected:
private:
	char *m_data;
};


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


String::String(const String &another)
{
	m_data = new char[strlen(another.m_data)+1];
	strcpy(m_data,  another.m_data);
}


String &String::operator = (const String *rhs)
{
	//异常安全
	if(this != rhs)
	{
		String strtmp(*rhs);
		char *tmp = strtmp.m_data;
		strtmp.m_data = m_data;
		m_data = tmp;
	}

	return *this;
}


ostream& operator <<(ostream &os, const String&str)
{
	os<<str.m_data;
	return os;
}
String::~String()
{
	delete[] m_data;
}
void main()
{

	String str("asdasd");
	String str1(str);
	String str2 = str1;
	cout<<str1<<endl;
	cout<<str2<<endl;

	return ;
}



   

你可能感兴趣的:(String,OS,null,delete,include,iostream)