问题描述
我构建了我自己的字符串类,其中我使用char * str
下面是一段代码
从下面代码片段,在param构造函数和复制构造函数中
cstr = str; //这部分语句工作正常。
但是为什么我需要使用new然后strcpy来分配内存?
cstr = new char [strlen(str)+1];
strcpy(cstr,str);
都可以。但为什么选择动态分配方法呢?
我尝试过:
i constructed my own string class where i use char* str
the below is the piece of code
From below code snippet, In param constructor and copy constructor
cstr = str; //this part of statement works fine.
but even then why i need to allocate memory using new and then strcpy required?
cstr = new char[strlen(str) +1];
strcpy(cstr, str);
both works fine. but why to choose dynamic allocation method?
What I have tried:
class CString
{
private:
char* cstr;
public:
CString();
CString(char* str);
CString(CString& str);
~CString();
operator char*();
//operator const char*();
CString operator+(const CString& q)const;
CString operator=(const CString& q);
};
CString::CString()
{
cout << "constructor" << endl;
cstr = 0;
}
CString::CString(char *str)
{
cout << " param constructor" << endl;
//cstr = str;// this works fine even then we allocating with new why???
cstr = new char[strlen(str) +1];
strcpy(cstr, str);
}
CString::CString(CString& q)
{
cout << " copy constructor" << endl;
if (this == &q)
return;
cstr = q.cstr;
//cstr = new char[strlen(q.cstr) + 1];
//strcpy(cstr, q.cstr);
}
CString::~CString()
{
//if (cstr)
// delete[] cstr;
}
CString::operator char*()
{
cout << " operatorcahr*" << endl;
return cstr;
}
//CString::operator const char* ()
//{
// cout << " const operatorcahr*" << endl;
// return cstr;
//}
CString CString::operator +(const CString &q) const
{
cout << "operator +*" << endl;
CString s;
s.cstr = new char[strlen(cstr) + strlen(q.cstr) + 1];
strcpy(s.cstr, cstr);
strcat(s.cstr, q.cstr);
return s;
}
CString CString::operator =(const CString &q)
{
cout << "operator =" << endl;
if (this != &q)
{
//if (cstr)
//delete[] cstr;
cstr = new char[strlen(q.cstr) + 1];
strcpy(cstr, q.cstr);
}
return *this;
}
int _tmain(int argc, _TCHAR* argv[])
{
CString a = CString("Hello") + CString(" World");
cout << a << endl;
getchar();
return 0;
}
推荐答案
CString CString::operator =(const CString &q)
{
cout << "operator =" << endl;
if (this != &q)
{
// No need to check if cstr is NULL.
// delete does nothing in this case.
delete[] cstr;
// But check here if q.cstr is NULL!
if (q.cstr)
{
cstr = new char[strlen(q.cstr) + 1];
strcpy(cstr, q.cstr);
}
// String is empty now
else
cstr = 0;
}
return *this;
}
CString::~CString()
{
delete[] cstr;
}
一旦实现了赋值运算符,它就可以被其他函数使用:
Once you have implemented the assignment operator, it can be used by other functions:
CString::CString(const CString& q)
{
cout << " copy constructor" << endl;
*this = q;
}
知道这一点,最好有一个 CString :: CString(const char * s)
赋值运算符,因为它可以用于多个复制构造函数。
Knowing this it might be better to have a CString::CString(const char *s)
assignment operator instead because that can be used for multiple copy constructors.
这篇关于为什么char指针被赋予new的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!