#include <iostream>
#include <cstring>
using namespace std;
//写一个string类
class String{
private:
char *m_str; //指针成员
public:
String(const char *str=""):m_str(strcpy(new char[str?strlen(str)+1:1],str?str:"")){
//m_str = new char[str?strlen(str)+1:1];
//strcpy(m_str,str?str:"");
//m_str = strcpy(new char[str?strlen(str)+1:1],str?str:"");
/*
if(str == NULL){
m_str = new char[1];
strcpy(m_str,"");//m_str[0] = '\0';
}else{
m_str = new char[strlen(str)+1];
strcpy(m_str,str);
}
*/
}
String(const String& s):m_str(strcpy(new char[strlen(s.m_str)+1],s.m_str)){
//m_str = new char[strlen(s.m_str)+1];
//strcpy(m_str,s.m_str);
}
String& operator=(const String& s){
if(this != &s){
/*
delete [] m_str;
m_str = new char[strlen(s.m_str)+1];
strcpy(m_str,s.m_str);
*/
/*
char *pt = new char[strlen(s.m_str)+1];
strcpy(pt,s.m_str);
delete [] m_str;
m_str = pt;
*/
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; //s4(s1) //拷贝构造函数
//s3 = s2;// 在进行赋值 调用拷贝赋值函数
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;
//如果返回的是String& 那么结果为Hello 如果没有引用 结果为world
//如果有const则编译报错
(ss3 = ss2) = ss1;// (ss3.operator=(ss2)).operator=(ss1)
cout << ss3.c_str() << endl;
int a,b,c;
(a = b) = c;
return 0;
}
C++String的实现
最新推荐文章于 2024-06-30 20:23:11 发布