string.cc

来自「资深C++讲师授课代码」· CC 代码 · 共 56 行

CC
56
字号
#include <iostream>
using namespace std;
#include <cstring>

class String{
	char* str;
public:
	String(){
		str = new char[1];
		*str = '\0';
		cout << "new " << (void*)str << endl;
	}
	String(const char* s){
		str = new char[strlen(s)+1];
		strcpy(str, s);
		cout << "new " << (void*)str << endl;
	}
	~String(){
		cout << "delete " << (void*)str << endl;
		delete[] str; str=NULL;
	}
	friend ostream& operator<<(ostream& o, const String& s){
		o << s.str;
		return o;
	}
	String operator+(const String& s2)const{
		char buf[1000];
		strcpy(buf, str);
		strcat(buf, s2.str);
		return String(buf);
	}
	String& operator=(const String& s2){
		if(this!=&s2){
			cout << "delete " << (void*)str << endl;
			delete[] str;
			str = new char[strlen(s2.str)+1];
			strcpy(str, s2.str);
			cout << "new " << (void*)str << endl;
		}
		return *this;
	}
};
int main()
{
	String s1;
	String s2("morning");
	cout << "s1=" << s1 << endl;
	cout << "s2=" << s2 << endl;
	s1 = s2;//s1.operator=(s2)
	cout << s1+s2 << endl;
	cout << "------------------" << endl;
	s1 = String("good");
	cout << "------------------" << endl;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?