调试有十几个错误,请问错在哪里?
--------------------------
CTestString.h
----------------------------------------
#pragma onceclass CTestString
{
public:
CTestString(const char* str = NULL); // 普通构造函数
CTestString(const CTestString &other); // 拷贝构造函数
~CTestString(void); // 析构函数
CTestString & operate = (const CTestString &other); // 赋值函数private:
char* m_data; // 用于保存字符串};
----------------------------
CTestString.cpp
-------------------------------------------------------
#include "TestString.h"
#include <string>using namespace std;// 普通构造函数
CTestString::CTestString(const char* str)
{
if (NULL == str)
{
m_data = new char[1];
*m_data = '\0';
}
else
{
int len = strlen(str);
m_data = new char[len+1];
strcpy(m_data, str);
}
}// 拷贝构造函数
CTestString::CTestString(const CTestString &other)
{
int len = strlen(other.m_data);
m_data = new char[len+1];
strcpy(m_data, other.m_data);
}// 析构函数
CTestString::~CTestString(void)
{
delete [] m_data;
}// 赋值函数
CTestString & CTestString::operate = (const CTestString &other)
{
// (1)检查自赋值
if (this == &other)
{
return *this;
} // (2)释放原有内存资源
delete [] m_data; // (3)分配新的内存资源并复制内容
int len = strlen(other.m_data);
m_data = new char[len+1];
strcpy(m_data, other.m_data); // (4)返回本对象的引用
return *this;
}
--------------------------
main.cpp
----------------------------------------------------
#include "TestString.h"
#include <iostream>using namespace std;int main(void)
{
const char* ch = "abcd";
CTestString myString(ch); cout << "普通构造函数:" << myString << endl; return 0;
}

解决方案 »

  1.   

    经典的面试题目
    #include "stdafx.h"#include<iostream>
    using namespace std;class String
    {
    public:
    String(const char *str=NULL);
    String(const String &other);
    ~String(void);
    String &operator =(const String &other);
    private:
    char *m_data;
    };String::String(const char *str)
    {
    cout<<"构造函数被调用了"<<endl;
    if(str==NULL)//避免出现野指针,如String b;如果没有这句话,就会出现野
    //指针
    {
    m_data=new char[1];
    *m_data='\0';
    }
    else
    {
    int length=strlen(str);
    m_data=new char[length+1];
    strcpy(m_data,str);
    }
    }
    String::~String(void)
    {
    delete m_data;
    cout<<"析构函数被调用了"<<endl;
    }String::String(const String &other)
    {
    cout<<"赋值构造函被调用了"<<endl;
    int length=strlen(other.m_data);
    m_data=new char[length+1];
    strcpy(m_data,other.m_data);
    }
    String &String::operator=(const String &other)
    {
    cout<<"赋值函数被调用了"<<endl;
    if(this==&other)//自己拷贝自己就不用拷贝了
    return *this;
    delete m_data;//删除被赋值对象中指针变量指向的前一个内存空间,避免
    //内存泄漏
    int length=strlen(other.m_data);//计算长度
    m_data=new char[length+1];//申请空间
    strcpy(m_data,other.m_data);//拷贝
    return *this;
    }
    void main()
    {
    String b;//调用构造函数
    String a("Hello");//调用构造函数
    String c("World");//调用构造函数
    String d=a;//调用赋值构造函数,因为是在d对象建立的过程中用a来初始化
    d=c;//调用重载后的赋值函数
    system("pause");
    }
    创建个控制台程序,拷贝进去,运行即可通过
      

  2.   

    首先4个函数没问题,要把它封装成一个独立的类TestString.cpp ,TestString.h这两个文件的写法有问题吗 ?