头文件
string.h
#include <iostream>
using namespace std;
class Str
{
char *m_str;
int m_len;
public:
Str();
Str(const char * st);
Str(const Str & st);
~Str();
Str & operator=(const Str &st);
friend ostream & operator<<(ostream & os, Str & st);
};
string.cpp
#include"string.h"
#include <cstring>
Str::Str()
{
m_str=NULL;
m_len=0;
}
Str::Str(const char * st)
{
cout<<st<<" constructed."<<endl;
m_len=strlen(st);
m_str=new char (m_len+1);
strcpy(m_str,st);
}
Str::Str(const Str & st)
{
cout<<st.m_str<<" constructed."<<endl;
m_len=st.m_len;
m_str=new char(m_len+1);
strcpy(m_str,st.m_str);
}
Str::~Str()
{
cout<<m_str<<" destroyed."<<endl;
delete [] m_str;
}
Str & Str::operator=(const Str &st)
{
if(this==&st)
return * this;
m_len=st.m_len;
delete m_str;
m_str=new char (st.m_len +1);
strcpy(m_str,st.m_str);
return *this;
}
ostream & operator<<(ostream & os, Str & st)
{
os<<st.m_str<<endl;
return os;
}
main.cpp
#include "string.h"
int main()
{
Str one;
Str two("hello");
Str three("the world");
cout<<two;
Str th=two;
cout<<th;
one=three;
cout<<one;
return 0;
}
运行环境为VS2008,编译无错误,但运行不正常,提示heap corruption detected.
且单步调试结果与运行结果不一致。
仔细检查发现是NEW 后使用应为中括号不是括号,改正后错误消失。
此类错误一般要细心检察,单步调试多可找出错误。
错误如图: