头文件:
#ifndef _STRINGS_
#define _STRINGS_
#include <iostream>
using namespace std;
class Strings
{
friend ostream& operator<<(ostream& os, const Strings& s);
public:
Strings();
Strings(char *s);
Strings(const Strings &s);
Strings& operator = (const Strings& s);
Strings& operator + (const Strings& s);
Strings& operator + (const char *s);
~Strings(){
if(str != NULL)
delete [] str;
cout<<"~Strings() is called"<<endl;
}
void display();
private:
char *str;
};
#endif
源文件:
#include "strings.h"
#include <cstring>
#include <iostream>
using namespace std;
ostream& operator<<(ostream& os, const Strings& s)
{
cout<<s.str;
return os;
}
Strings::Strings()
{
str = new char('A');
cout<<"Strings (char *s) is called"<<endl;
}
Strings::Strings(char *s){
str = new char[strlen(s)+1];
if (str)
{
strcpy(str, s);
}
cout<<"Strings(char *s) is called"<<endl;
}
Strings::Strings(const Strings &s){
str = new char[strlen(s.str)+1];
if(str){
strcpy(str, s.str);
}
cout<<"Strings(const Strings &s) is called"<<endl;
}
Strings& Strings::operator =(const Strings &s)
{
if(this != &s){
if (str != NULL)
{
delete [] str; //防止内存泄露
}
str = new char[strlen(s.str)+1];
strcpy(str, s.str);
cout<<"Strings(const Strings &s) is called"<<endl;
}
return *this;
}
Strings& Strings::operator +(const Strings& s)
{
char *temp;
temp = new char[strlen(str)+strlen(s.str)+1];
strcpy(temp, str);
delete [] str;
strcat(temp, s.str);
str = temp;
return *this;
}
Strings& Strings::operator + (const char *s)
{
char *temp;
temp = new char[strlen(str)+strlen(s)+1];
strcpy(temp, str);
delete [] str;
strcat(temp, s);
str = temp;
return *this;
}
void Strings::display() {
char *p = str;
while (*p != '\0')
{
cout<<*p;
p++;
}
cout<<endl;
cout<<"display is called"<<endl;
}