C++ 类,运算符重载--->代码
来源:互联网 发布:淘宝店卖保健品 编辑:程序博客网 时间:2024/05/18 18:54
一个不错的学习文档: http://www.kuaipan.com.cn/file/id_204066781134907.htm 在线查看:/*mystring.h*/#include <iostream>using namespace std;class MyString{friend ostream &operator<<(ostream &,const MyString &);friend MyString operator+(const MyString&,const MyString &);public:MyString(const char *);MyString(const MyString &);~MyString(void);MyString&operator=(const MyString &);int length(void)const;bool isEmpty(void)const;private:char *data;int len;};
/*mystring.cpp*/
#include <iostream>
#include "mystring.h"
#include <cstring>
using namespace std;
MyString::MyString(const char *str)
{
cout<<"ctor"<<endl;
if(str==NULL)
{
len=0;
data=new char[1];
*data='\0';
}else{
len=strlen(str);
data=new char[len+1];
strcpy(data,str);
}
}
MyString::MyString(const MyString &other)
{
cout<<"copy ctor"<<endl;
len=other.len;
data=new char [len+1];
strcpy(data,other.data);
}
MyString::~MyString(void)
{
cout<<"assignment"<<endl;
delete[]data;
}
MyString &MyString::operator=(const MyString &other)
{
cout<<"assignment"<<endl;
if(this==&other) //注意自己
return *this;
delete[]data;//注意以前的长度不狗
len=other.len;
data=new char[len+1];
strcpy(data,other.data);
return *this;
}
int MyString::length(void )const
{
return len;
}
bool MyString::isEmpty(void )const
{
return len==0;
}
ostream& operator<<(ostream &out,const MyString &str)
{
out<<str.data;
return out;
}
MyString operator+(const MyString &a,const MyString &b)
{
cout<<"concatenate"<<endl;
MyString temp("");
delete[]temp.data;
temp.len=a.len+b.len;
temp.data=new char[temp.len+1];
strcpy(temp.data,a.data);
strcat(temp.data,b.data);
return temp;
}
/*main.cpp*/#include <iostream>#include "mystring.h"using namespace std;int main(){cout<<"----------NO.1--start----------"<<endl;MyString str("Hello"); //NO.1cout<<"----------NO.1--END----------"<<endl;cout<<"----------NO.2--start----------"<<endl;MyString str1=str; //NO.2cout<<"----------NO.2--END----------"<<endl;cout<<"Length of str1:"<<str1.length()<<endl;cout<<"Value of str1:"<<str<<endl;cout<<"----------NO.3--start----------"<<endl;MyString str2="";//NO.3cout<<"----------NO.3--END----------"<<endl;cout<<"ls str2 empty()?"<<(str2.isEmpty()?"ture":"false")<<endl;cout<<"----------NO.4--start----------"<<endl;str2="world"; //NO.4cout<<"----------NO.4--END----------"<<endl;cout<<"Now value of str2"<<str2<<endl;cout<<"Now value of str:"<<str1+str2<<endl;cout<<"Value of another expression:"<<str1+"__world"<<endl;cout<<"Value of yet another expression:"<<"hello,"+str2<<endl;cout<<"----------NO.5--start----------"<<endl;MyString str3=str1+str2; //NO.5cout<<"----------NO.5--END----------"<<endl;cout<<"Value of str3:"<<str3<<endl;return 0;}