声明一个类MyString,定义它里面的各个函数

时间:2022-08-29 21:53:19

题目:类CMyString的声明如下:class CMyString{public: CMyString(char* pData = NULL); CMyString(const CMyString& str); ~CMyString(void); CMyString& operator = (const CMyString& str);private: char* m_pData;};

 

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

class MyString
{
public:
	//MyString();
	MyString(char *str =NULL);
	~MyString();
	MyString(const MyString &other);
	MyString & operator=(const MyString &other);
	void print();
private:
	char *m_data;
};
MyString::MyString(char *str)
{   
	if(str==NULL)
	{
		//m_data = (char *)malloc(sizeof(char));
		m_data = new char[1];
		*m_data ='\0';
	}
	else	
	{
        int len = strlen(str);
     	//m_data = (char *)malloc(sizeof(char)*len+1);
		m_data = new char[len+1];
	    strcpy(m_data ,str);
	}	
}

MyString::~MyString()
{
	//free(m_data);
	delete[]m_data;
}
MyString::MyString(const MyString &other)
{

	int len =strlen(other.m_data);
	//m_data = (char *)malloc(sizeof(char)*len+1);
	m_data = new char[len+1];
	strcpy(m_data ,other.m_data);
}
MyString & MyString::operator=(const MyString &other)
{
	if(this==&other)
	{
		return *this;
	}
	//free(m_data);
	delete[]m_data;
	m_data = NULL;
	int len =strlen(other.m_data);
	//m_data = (char *)malloc(sizeof(char)*len+1);
	m_data = new char[len+1];
	strcpy(m_data ,other.m_data);
	return *this;

}

void MyString::print() 
{
	printf("%s",m_data);
}
void main()
{
   MyString str1("hello");
   MyString str2("word");
   MyString str3 = str1;
   MyString str4 ;
   str4 = str2;
   str1.print();
   str2.print();
   str3.print();
   str4.print();	    
}