鍍金池/ 問答/C++/ cout打印動(dòng)態(tài)字符數(shù)組

cout打印動(dòng)態(tài)字符數(shù)組

#include <iostream>
using namespace std;

class mstring
{
public:
    mstring(const char* str)
    {
        length = strlen(str);
        m_char = new char(length + 1);
        
        strcpy_s(m_char, length + 1, const_cast<char*>(str));
    }

    friend ostream& operator<<(ostream& out,const mstring& str)
    {
        if (NULL != str.m_char)
        {
            out << str.m_char;
            return out;
        }
    }

    ~mstring()
    {
        if (m_char != NULL)
        {
            delete m_char;
            length = 0;
        }       
    }

    char* m_char;
    int length;

};

int main()
{
    mstring* mstr = new mstring("Hello World!");
    cout << mstr;

    return 0;
}`

為什么內(nèi)存會(huì)出錯(cuò)???

回答
編輯回答
陌如玉

char()改成char[]

2018年3月12日 17:49
編輯回答
雨萌萌

首先你創(chuàng)建的mstr沒釋放,new后面沒delete
其次友元函數(shù)里面沒有覆蓋,if要是沒進(jìn)去返回什么呀?
還有就是樓上的 new char() -> new char[]

2017年8月28日 11:51