#include <iostream>
#include <cstring>
using namespace std;
class String{
private:
char *m_str;
public:
String(const char *str=""):m_str(strcpy(new char[str?strlen(str)+1:1],str?str:"")){
}
String(const String& s):m_str(strcpy(new char[strlen(s.m_str)+1],s.m_str)){
}
String& operator=(const String& s){
if(this != &s){
String stmp(s);
swap(stmp.m_str,m_str);
}
return *this;
}
~String(void){
if(m_str != NULL){
delete [] m_str;
m_str = NULL;
}
}
const char * c_str(){
return m_str;
}
int length()const{
return strlen(m_str);
}
char& operator[](int index){
return m_str[index];
}
const char& operator[](int index)const{
return m_str[index];
}
};
int main(){
String s1("Hello world");
String s2(s1);
String s3;
String s4 = s1;
s3.operator=(s2);
cout << s1.c_str() << endl;
cout << s2.c_str() << endl;
cout << s3.c_str() << endl;
String ss1("Hello");
String ss2("world");
String ss3;
(ss3 = ss2) = ss1;
cout << ss3.c_str() << endl;
int a,b,c;
(a = b) = c;
return 0;
}
|