#include <iostream>
#include <cassert>
class String
{
public:
String();
String(const char *);
~String();
String(const String &s);
String& operator= (const char *);
String& operator= (const String &s1 );
// String operator+ (const String &s1,const String &s2);
//在类内实现运算符重载的话,双目运算符只需要一个参数
String operator+ (const String &s);
friend ostream& operator<<(ostream& out,const String& s); //实现流插入运算符重载应使用友员函数
// ostream& operator<< (ostream &out); //关于在类内实现流插入运算符是错误的
private:
char *ptr;
};
String::String()
{
ptr=(char *)malloc(1);
*ptr='/0';
}
String::String(const char *str)
{
if(str==NULL)
{
ptr=(char *)malloc(1);
*ptr='/0';
}
else
{
ptr=(char *)malloc(strlen(str)+1);
strcpy(ptr,str);
}
}
String::~String()
{
free(ptr);
}
String::String(const String &s)
{
assert(s.ptr!=NULL);
int len=strlen(s.ptr);
ptr=(char *)malloc(len+1);
strcpy(ptr,s.ptr);
}
String& String::operator=(const char *str)
{
assert(str!=NULL);
if(str==ptr)
{
return *this;
}
free(ptr);
int len=strlen(str);
ptr=(char *)malloc(len+1);
strcpy(ptr,str);
return *this;
}
String& String::operator=(const String& s1)
{
assert(s1.ptr!=NULL);
if(this==&s1)
{
return *this;
}
free(ptr);
int len=strlen(s1.ptr);
ptr=(char *)malloc(len+1);
strcpy(ptr,s1.ptr);
return *this;
}
*/
/*
String String::operator+(const String& s1,const String& s2)
{
String temp;
free(temp.ptr);
temp.ptr=(char *)malloc(strlen(s1.ptr)+strlen(s2.ptr)+2);
strcpy(temp.ptr,s1.ptr);
srecat(temp.ptr,s2.ptr);
return temp;
}
*/
String String::operator+(const String &s)
{
String temp;
free(temp.ptr);
temp.ptr=(char *)malloc(strlen(this->ptr)+strlen(s.ptr)+2);
strcpy(temp.ptr,this->ptr);
strcat(temp.ptr,s.ptr);
return temp;
}
ostream& operator <<(ostream &out, const String& s)
{
out<<s.ptr;
return out;
}
/*
ostream& String::operator <<(ostream &out)
{
printf("%s",ptr);
// out<<s.ptr<<endl;
return out;
}
*/
int main()
{
String ss1("hello");
String ss2="world";
String ss3=ss2;
String ss4=ss1+ss2;
cout<<ss1<<endl<<ss2<<endl<<ss3<<endl<<ss4<<endl;
// cout<<ss4;
cout<<endl;
return 0;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
编写此类时注意的几点:
1,编译器VC6.0和VS2005对友员函数的支持不好,编译的时候会出现“无法访问类的私有成员“的提示
解决方法:
1.将#include <iostream> using namespace std;改为#include <iostream.h>
2.在#include <iosteam> using namespace std;后面加上class String; ostream& operator <<(ostream &, const String& );
2,关于在类内实现流插入运算符是错误的(潭浩强的《C++程序设计》),应该使用友员函数重载运算符
(见C++primer p436),因为它的左值是cout