Toyears 2015-05-30 13:53 采纳率: 100%
浏览 2300
已采纳

关于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条回答 默认 最新

  • 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;
    }

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献