String类实现

#include <iostream>
#include<string.h>

using namespace std;

class String{
	public:
		String(const char* cstr = 0);
		String(const String& cstr);
		String& operator=(const String& str);
		~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];
		*my_data = '\0';
	} 
}

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

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

inline String& String::operator=(const String& str)
{
	if(&str == this)
		return *this;
	delete[] my_data;
	my_data = new char[strlen(str.my_data) + 1];
	strcpy(my_data, str.my_data);
	return *this;
}

上一篇:验证回文串——leetcode125


下一篇:2021-09-18