序言:本篇文章用于记录C++学习的构造器、拷贝构造器、析构器、赋值运算符重载的记录,该文章以自己实现stringl类型为实例进行练习。
1.mystring.h文件(函数声明)
class mystring{
public:
mystring(const char*p = NULL);
mystring(const mystring & another);
mystring& operator=(const mystring & another);
~mystring();
char * c_str();
private:
char * _str;
};
2.mystring.cpp文件(函数实现)
#include <iostream>
#include "mystring.h"
#include <string.h>
using namespace std;
mystring::mystring(const char* p){
if(p == NULL){
_str = new char[1];
*_str = '\0';
}else{
int len = strlen(p);
_str = new char[len+1];
strcpy(_str,p);
}
}
mystring::mystring(const mystring & another)
{
int len = strlen(another._str);
_str = new char[len+1];
strcpy(_str,another._str);
}
mystring& mystring::operator=(const mystring & another)
{
if(this == &another)
return *this;
delete []this->_str;
int len = strlen(another._str);
this->_str = new char[len+1];
strcpy(this->_str,another._str);
return *this;
}
char* mystring::c_str()
{
return _str;
}
mystring::~mystring()
{
delete []_str;
}
3.mystringmain.cpp文件(函数调用)
#include <iostream>
#include "mystring.h"
using namespace std;
int main()
{
string s1;
string s2("usa");
cout<<s1.c_str()<<endl;
cout<<s2.c_str()<<endl;
cout<<"--------------------"<<endl;
mystring ms("china");
mystring ms2(ms);
mystring ms3;
ms3=ms2;
mystring ms4;
ms4.operator=(ms3);
cout<<ms.c_str()<<endl;
cout<<ms2.c_str()<<endl;
cout<<ms3.c_str()<<endl;
cout<<ms4.c_str()<<endl;
return 0;
}
|