⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 soln8_03.cpp

📁 Wrox.Ivor.Hortons.Beginning.Visual.C.Plus.Plus.2008 With sourcecode
💻 CPP
字号:
// Soln8_03.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(char c, int count=1);
   CSimpleString(int i);

   ~CSimpleString();

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

// Contructor - repeated given character
CSimpleString::CSimpleString(char c, int count) : len(0), buff(0)
{
   len = count;
   if (len > 0)
   {
      buff = new char[len+1];
      memset(buff, c, len);
      buff[len] = '\0';
   }
}

// Constructor - from an integer
CSimpleString::CSimpleString(int i) : len(0), buff(0)
{
   char sTmp[20];
   _itoa_s(i, sTmp, 20, 10);

   len = strlen(sTmp);
   if (len > 0)
   {
      buff = new char[len+1];
      strcpy_s(buff, len+1, sTmp);
   }
}

// Constructor
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);
      }
   }
}

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

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

// Assignment operator - does not deal with str = str
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;
   CSimpleString marker = CSimpleString('*', 30);
   marker.print();
   cout << endl;

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

   cout << "\"" << endl;

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

   int n = 7890;

   CSimpleString nStr = CSimpleString(n);

   cout << n << " as a string is \"";
   nStr.print();
   cout << "\"" << endl;

   marker.print();
   cout << endl;
   return 0;
}

⌨️ 快捷键说明

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