C++面向对象:实现string类

//string.h
#pragma once
class String {
public:
	String(const char* cstr = 0);
	String(const String& str);
	~String();
	
	String& operator = (const String& str);
	String& operator += (const String& str);
	
	char* get_c_str() const { return m_data; }
private:
	char* m_data;
};

#include <cstring>
inline String::String(const char* cstr) {
	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(const String& str) {
	m_data = new char[strlen(str.m_data) + 1];
	strcpy(m_data, str.m_data);
}

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

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

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

  

//string.cpp
#include "string.h"
#include <iostream>
using namespace std;

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

int main()
{
	String s1("hello");
	String s2("world!!!");
	
	String s3(s2); //String s3 = s2 含typename为拷贝构造
	cout << s1 << " " << s2 << " " << s3 << endl;

	s3 = s1; //不含typename不是拷贝构造, 调用operator=
	cout << s1 << " " << s2 << " " << s3 << endl;

	s3 += s2;
	cout << s3 << endl;

	String s4;
	String s5(s4);
	cout << s4 << " " << s5 << endl;
	s5 += s2;
	cout << s4 << " " << s5 << endl;
	return 0;
}

  执行结果:

hello world!!! world!!!
hello world!!! hello
helloworld!!!

 world!!!

 

posted @ 2023-02-22 02:02  karinto  阅读(22)  评论(0)    收藏  举报