C++ String 的构造函数,析构函数等

@wanqiuz 2018-07-25 12:14:08发表于 wanqiuz/blog-articles

头文件

class String
{
public:
  String (const char* c);
  ~String ();
  String (const String& s);
  String& operator= (const String& s);
  friend ostream& operator<< (ostream& o, const String& s);
private:
  char* data;
}

构造函数

String::String (const char* c)
{
  if (c == NULL)
  {
    data = new char[1];
    data[0] = "\0";
  }
  else
  {
    data = new char[strlen(c) + 1];
    strcpy(data, c);
  }
}

析构函数

String::~String ()
{
  delete[] data;
}

拷贝构造函数

String::String (const String& s)
{
  data = new char[strlen(s.data) + 1];
  strcpy(data, s.data);
}

赋值函数

String& String::operator= (const String& s)
{
  if (&s == this)
    return *this;

  delete[] data;
  data = new char[strlen(s.data) + 1];
  strcpy(data, c.data);
  return *this;
}

流打印

ostream& operator<< (ostream& o, const String& s)
{
  o << s.data;
  return o;
}