C++字符串类实现(转)

来源:互联网 发布:json解析成java对象 编辑:程序博客网 时间:2024/05/18 01:30

C++字符串类实现,包括默认构造函数,带一个参数的构造函数,copy构造函数,赋值运算,加法运算等 

在VC6.0下编译通过

by : kvew    www.smatrix.org/bbs   www.secoder.org/bbs

main函数:

#include <iostream>
#include "strings.h"

using namespace std;

int main(){

 Strings  s3;
 Strings  s4;
 Strings  s5;
 s3.display();

 Strings s1("hello");
 s1.display();
 Strings s2(s1);
 s2.display();
 s3 = s2;
 s3.display();
 s4 = s1+s2;
 s4.display();
   
 s5 = s4 + "good";
 s5.display();

return 0;
}

strings.h函数

#ifndef _STRINGS_
#define _STRINGS_
#include<iostream>
using namespace std;

class Strings{

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;
 }

 display();

private:
 char *str;


};

#endif

 

strings.cpp函数

#include "strings.h"
#include <iostream>
using namespace std;

Strings::Strings(){                                   //  默认构造函数
 
  str = new  char('A');    //初试化为字符A

  //str = "nothing";          试试如此初试话 :-)  呵呵
   cout<<"Strings 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){   //  copy构造函数
    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){          // 如果str不是它本身
  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;
}


Strings::display(){                    //  显示函数
 char *p=str;
 while(*p != '/0'){
   cout<<*p;
   p ++;
  }
  cout<<endl;
cout<<"display is called  "<<endl;
 }

 

原创粉丝点击