View Full Version : class cmystring
phatngoit
11-10-2010, 03:05 PM
cho em hỏi class cmytring mình phải viết như thế nào. Em chỉ vừa mới học nó thôi nên cũng không biết nhiều về nó. Mong anh chị giúp đỡ dùm em thêm
khigiadano
11-10-2010, 11:51 PM
Thấy cái này trên google nà.
// MyString.cpp: implementation of the CMyString class.
//
//////////////////////////////////////////////////////////////////////
#include <string>
#include "MyString.h"
using namespace std;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
// Default ctor
CMyString::CMyString()
{
m_pString = NULL;
}
// Construct object from C-style string
CMyString::CMyString(const char *str)
{
m_pString = new char[strlen(str) + 1];
strcpy(m_pString, str);
}
// Construct object from int
CMyString::CMyString(int nInt)
{
char intString[64];
sprintf(intString, "%d", nInt);
m_pString = new char[strlen(intString) + 1];
strcpy(m_pString, intString);
}
// Copy ctor
CMyString::CMyString(const CMyString &src)
{
m_pString = new char[strlen(src.getString()) + 1];
strcpy(m_pString, src.getString());
}
// Dtor
CMyString::~CMyString()
{
delete [] m_pString;
m_pString = NULL;
}
// Assignment operator
CMyString& CMyString::operator =(const CMyString &src)
{
if(this == &src) { // Why is this important?
return *this;
}
delete [] m_pString; // Cleanup "this" object
// Next two lines are just like copy ctor!
m_pString = new char[strlen(src.getString()) + 1];
strcpy(m_pString, src.getString());
return *this;
}
// Accessor
const char* CMyString::getString() const
{
return m_pString;
}
http://www1.coe.neu.edu/~ctd/ISY240/code/Conversions/MyString.cpp.html (http://www1.coe.neu.edu/%7Ectd/ISY240/code/Conversions/MyString.cpp.html)
vBulletin® v3.8.3, Copyright ©2000-2012, Jelsoft Enterprises Ltd.