编程语言
首页 > 编程语言> > c++ 自行实现一个String类

c++ 自行实现一个String类

作者:互联网

#include <iostream>
#include "stddef.h"
#include <cstring>
using namespace std;

class String {
private:
	uint32_t len; // 注意 private
	char* str_p;
public:
	String(const char* str); // 构建函数无返回值
	~String(); // 注意析构函数
	String& operator+(const char* str);   // 注意const char *
	String& operator=(const String& str); // 注意返回值 String& 和 参数 const String &
	const char* to_str() const;  // 尾部const
};
String::String(const char* str) {
	if (NULL == str) {
		uint32_t len = 0;
		str_p = new char[len+1];
		strcpy(str_p, "");
	} else {
		uint32_t len = strlen(str);
		str_p = new char(len+1);
		strcpy(str_p, str);
	}
}
String::~String() {
	delete[] str_p;
	len = 0;
}
String& String::operator+(const char* str) {
	if (NULL == str) {
		return *this;
	} else {
		uint32_t new_len = len+strlen(str);
		char* new_tmp = new char[new_len];
		strcpy(new_tmp, str_p);
		strcat(new_tmp, str);
		delete[] str_p;
		str_p = new_tmp;
	}
	return *this;
}
String& String::operator=(const String& str) {
	if (this == &str) {
		return *this;
	} else {
		uint32_t new_len = strlen(str.to_str());
		delete[] str_p;
		str_p = new char[new_len];
		strcpy(str_p, str.to_str());
	}
	return *this;
}
const char* String::to_str() const{
	return str_p;
}

int main() {
	String str("hello world");
	str = str + " 2";
	cout<<str.to_str()<<endl;
}

  

标签:char,const,String,c++,自行,len,str,new
来源: https://www.cnblogs.com/sailrancho/p/11781203.html