qq_26496339
Toyears
2015-05-30 13:53
采纳率: 100%
浏览 2.2k

关于C++构造函数生成空字符串。。。

class CString
{

char m_buff[MAXLENGTH];
public:
CString(); //构造函数1,设置为空字符串

~CString();
friend ostream& operator<<(ostream& Out, const CString& S); //输出字 符串
char operatorconst;
};
CString::CString()
{
m_buff[0]=NULL;
}

char CString::operatorconst
{
return m_buff[i];
}
ostream& operator<<(ostream& Out, const CString& S)
{
return Out<<S.m_buff<<endl;
}
CString::~CString()
{
delete[] m_buff;
}
void main()
{
CString s1;

cout << s1;

}
这是其中一段

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • tujiaw
    ningto.com 2015-06-01 04:24
    已采纳

    // MyString.cpp : 定义控制台应用程序的入口点。
    //
    #include "stdafx.h"
    #include
    #include
    class MyString
    {
    public:
    MyString(const char str = NULL);
    MyString(const MyString &other);
    ~MyString(void);
    MyString & operator = (const MyString &other);
    int OutputStr(void);
    private:
    char *m_data;
    };
    MyString::MyString(const char *str)//普通的构造函数
    {
    if (str == NULL)
    {
    m_data = new char[1];
    *m_data = '/0';
    }
    else
    {
    int length = strlen(str);
    m_data = new char[length + 1];
    strcpy(m_data, str);
    }
    }
    MyString::MyString(const MyString &other)//拷贝构造函数
    {
    int length = strlen(other.m_data);
    m_data = new char[length + 1];
    strcpy(m_data, other.m_data);
    }
    MyString::~MyString(void)
    {
    delete [] m_data;
    }
    MyString & MyString::operator = (const MyString &other)//赋值操作
    {
    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;
    }
    int MyString::OutputStr(void)
    {
    int length = 0;
    length = strlen(m_data);
    printf("the output string is : %s", m_data);
    return length;
    }
    int _tmain(int argc, _TCHAR
    argv[])
    {
    MyString str("hello, world");//进入普通构造函数
    MyString str2 = str;//初始化,进入拷贝构造函数
    MyString str3(str);//初始化,进入拷贝构造函数
    str2 = str;//赋值,进入赋值操作
    str2.OutputStr();
    //MyString *str = new MyString("hello, world");//普通构造函数
    //MyString *str2 = new MyString(*str);//拷贝构造函数
    //*str2 = *str;//赋值操作
    //str2->OutputStr();
    getchar();
    return 0;
    }

    点赞 评论
  • caozhy

    m_buff[0]=NULL;
    ->
    m_buff[0]='\0';

    点赞 评论
  • caozhy
     代码问题很多
    delete[] m_buff;
    这里不要delete,因为你不是动态分配
    return Out<<S.m_buff<<endl;
    ->
    Out<<S.m_buff<<endl;
    return Out;
    
    点赞 评论

相关推荐