San*_*099 6 c++ string overloading reference operator-keyword
我正在尝试编写自己的C++ String类,用于教育和需求目的.
首先,我对操作员知之甚少,这就是我想学习它们的原因.我开始编写我的课程但是当我运行它时会阻止程序,但不会发生任何崩溃.
在进一步阅读之前,请先查看以下代码:
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);
};
Run Code Online (Sandbox Code Playgroud)
首先,我不太确定我宣布一切正确.我尝试谷歌搜索它,但所有关于重载的教程解释了基本的ideea,这很简单,但缺乏解释如何以及何时调用每个东西.例如,在my =运算符中,程序调用CString(CString&str); 但我不知道为什么.
我还附上了下面的cpp文件:
CString::CString()
{
cstr=0;
}
CString::CString(char *str)
{
cstr=new char[strlen(str)];
strcpy(cstr,str);
}
CString::CString(CString& q)
{
if(this==&q)
return;
cstr = new char[strlen(q.cstr)+1];
strcpy(cstr,q.cstr);
}
CString::~CString()
{
if(cstr)
delete[] cstr;
}
CString::operator char*()
{
return cstr;
}
CString::operator const char* ()
{
return cstr;
}
CString CString::operator +(const CString &q) const
{
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)
{
if(this!=&q)
{
if(cstr)
delete[] cstr;
cstr = new char[strlen(q.cstr)+1];
strcpy(cstr,q.cstr);
}
return *this;
}
Run Code Online (Sandbox Code Playgroud)
为了测试我使用的代码就像这个
CString 一样简单a = CString("Hello")+ CString("World");
的printf(一);
我试过调试它,但在某一点上我迷路了.首先,它为"hello"和"world"调用构造函数2次.然后它在+运算符中就可以了.然后它调用空字符串的构造函数.之后它进入"CString(CString&str)",现在我迷路了.为什么会这样?在此之后我注意到我的包含"Hello World"的字符串在析构函数中(连续几次).我又一次非常困惑.再次从char*转换为Cstring后来回停止.它永远不会进入=运算符,但它也不会进一步发展.从未到达printf(a).
我使用VisualStudio 2010,但它基本上只是标准的c ++代码,因此我认为它不会产生那么大的差别
小智 4
该行:
cstr=new char[strlen(str)];
Run Code Online (Sandbox Code Playgroud)
应该:
cstr=new char[strlen(str) + 1];
Run Code Online (Sandbox Code Playgroud)
此外,自分配测试在复制构造函数中没有意义 - 您正在创建一个新对象 - 它不可能与任何现有对象具有相同的地址。并且复制构造函数应该采用 const 引用作为参数,
如果在您的代码中,您期望使用赋值运算符,那么您的期望是错误的。这段代码:
CString a = CString("Hello") + CString(" World");
Run Code Online (Sandbox Code Playgroud)
本质上是一样的:
CString a( CString("Hello") + CString(" World") );
Run Code Online (Sandbox Code Playgroud)
这是复制构造,而不是赋值。a 构造完成后,临时 CString“Hello world”将被销毁(调用析构函数)。
基本上,听起来您的代码或多或少按预期工作。