soln8_2.cpp

来自「Visual C++ 2005的源代码」· C++ 代码 · 共 80 行

CPP
80
字号
// Soln8_2.cpp

#include <iostream>                   // For stream input/output
#include <cstring>

using std::cout;
using std::endl;

class CSimpleString
{
private:
   size_t len;
   char* buff;
public:
   CSimpleString(const char* p = 0);
   CSimpleString(const CSimpleString& s);
   ~CSimpleString();

   CSimpleString& operator=(const CSimpleString& rhs);
   void print();
};

CSimpleString::CSimpleString(const char* p) : len(0), buff(0)
{
   if (p != 0)
   {
      len = strlen(p);
      if (len > 0)
      {
         buff = new char[len+1];
         strcpy_s(buff, len+1, p);
      }
   }
}

CSimpleString::CSimpleString(const CSimpleString& s)
{
   len = s.len;
   buff = new char[len+1];
   strcpy_s(buff, len+1, s.buff);
}

CSimpleString::~CSimpleString()
{
   delete buff;
}

CSimpleString& CSimpleString::operator=(const CSimpleString& rhs)
{
   len = rhs.len;
   delete buff;
   buff = new char[len+1];
   strcpy_s(buff, len+1, rhs.buff);

   return *this;
}

void CSimpleString::print()
{
   cout << buff;
}

int main()
{
   CSimpleString s1 = "hello";
   CSimpleString s2;

   s2 = s1;

   cout << "s1 = \"";
   s1.print();
   cout << "\"" << endl;

   cout << "s2 = \"";
   s2.print();
   cout << "\"" << endl;

   return 0;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?