📄 string.cc
字号:
#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 + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -