String Class

//String.h

#ifndef STRING_H_H

#define STRING_H_H

#include <cstring>

#include <iostream>

using std::ostream;

using std::istream;

using std::cout;

using std::cin;



class String

{

    friend ostream& operator<<(ostream&, String&);

  friend istream& operator>>(istream&, String&);

public:

    String(const char* psz=NULL);

    String(const String&);//直接初始化

    ~String();



    String& operator=(const String&);//复制初始化

    String operator+(const String&);

    int GetLength() const;

    int Compare(const String&) const;

private:

    char *data;

  int length;

};

#endif







//String.cpp

#include "String.h"



String::String(const char *psz)

{

   length = strlen(psz);

  data = new char[length + 1];

  for (int i=0; i<length; i++)

    data[i] = psz[i];

  data[length] = '\0';

}



String::String(const String& rhs)

{

  length = strlen(rhs.data);

  data = new char[length];

  char * tmp = rhs.data;

  while (*data++ = *tmp++);

  data[length] = '\0';

}



String::~String()

{    

  delete [] data;

}



String& String::operator=(const String& rhs)

{

    if (this == &rhs)

    return *this;

  

  delete [] data;

  length = rhs.length;

  data = new char[length]; 

  for (int i=0; i<length; i++)

    data[i] = rhs.data[i];

  data[length] = '\0';



  return *this; 

}



int String::GetLength() const

{

    return length;

}



String String::operator+(const String& rhs)

{

    int new_len = length + rhs.length;

  char * str = new char[new_len-1];



  int count = 0;

  for (int i=0; i<length; i++) {

    str[count] = data[i];

    count++;

  }

  for (int i=0; i<rhs.length; i++) {

    str[count] = rhs.data[i];

    count++;

  }

  str[new_len] = '\0';



  String tmp(str);

  *this = tmp;

  return *this;    

}



int String::Compare(const String& rhs) const

{

    return strcmp(data, rhs.data);

}



ostream& operator<<(ostream& os, String& str)

{

    os<<str.data;

    return os;

}



istream& operator>>(istream& is, String & str)

{

  is >> str.data;

  str.length = strlen(str.data);

  return is;

}







//main.cpp

#include "String.h"



int main()

{

    String str1("hello ");

    String str2("world!");

    String str3 = str1 + str2;

    cout<<str3;

    return 0;

}

 

 

你可能感兴趣的:(String)