注册 登录
编程论坛 C++教室

帮忙看看是哪里出了问题!

BlueMouse 发布于 2008-09-23 10:34, 540 次点击
程序代码:
#include <windows.h>

class CA
{
    private:
        const char *tValue;
    public:
        CA& operator=(const char* tNewValue);
        CA& operator+=(const char* tNewValue);
        operator const char*()
        {
            return this->tValue;
        }
        
};

CA& CA::operator=(const char* tNewValue)
{
    this->tValue = tNewValue;
    return *this;
}

CA& CA::operator+=(const char* tNewValue)
{
    char *pSz;

    pSz = new char(strlen(this->tValue)+strlen(tNewValue)+1);
    strcat(pSz,this->tValue);
    strcat(pSz,tNewValue);
    delete [] this->tValue;
    this->tValue = pSz;
    return *this;
}

int WINAPI WinMain(HINSTANCE hInstance,
                   HINSTANCE hPrevInstance,
                   LPSTR     lpCommandLine,
                   int         nShowCmd)
{
    CA myca;

    myca = "TEST INFORMATION\n";
    myca += "0123456789\n";
    myca += "0123456789\n";
    myca += "0123456789\n";
    myca += "0123456789\n";
    myca += "0123456789\n";
    myca += "0123456789\n";
    myca += "0123456789\n";
    myca += "0123456789\n";
    myca += "0123456789\n";
    myca += "0123456789\n";
    myca += "0123456789\n";
    myca += "0123456789\n";
    myca += "0123456789\n";
    myca += "0123456789\n";
    myca += "0123456789\n";
    myca += "0123456789\n";
    myca += "0123456789\n";
    myca += "0123456789\n";
    myca += "0123456789\n";
    myca += "0123456789\n";
    myca += "0123456789\n";
    myca += "0123456789\n";
    MessageBoxA(NULL,
                myca,
                "Debug information",
                MB_OK|MB_ICONINFORMATION);
    return 0;
}


可以运行! 但是字符串前面不知道怎么会多出一些乱码来!,难道是连接字符串的时候tValue的指向被修改了? 问题是肯定出在CA::operator+=里的! 但是是什么问题?如何解决呢?请懂的人教教!
3 回复
#2
BlueMouse2008-09-23 10:59
找出原因了!晕!
CA::operator函数改成这样就行了!
为什么呢!晕!最基本的概念问题!

我是这样认为的!
strcat 是用来连接字符串的,它是怎么样工作的呢!

strcat(char* a, const char* b);

strcat 首选会从 a 指向的地址起找出第一个 '\0' 字符串结标志
然后把 b 连接到这个 '\0' 的位置完成连接操作,
问题就出在这里了, new char 的时候申请到的堆空间并没有初始化空间无素,导致了 strcat 查找'\0'的时候出了问题,所以会得出你想不到的结果来,new char出来的堆空间要自己初始化一下就OK了!像下面这样!

CA& CA::operator+=(const char* tNewValue)
{
    char *pSz;
    int index;
    int nLength;
    nLength = strlen(this->tValue)+strlen(tNewValue);
    pSz = new char(nLength);
    for(index=0;index<nLength;index++)
    {
        pSz[index]='\0';
    }
    strcat(pSz,this->tValue);
    strcat(pSz,tNewValue);
    delete [] this->tValue;
    this->tValue = pSz;
    return *this;
}
#3
BlueMouse2008-09-23 11:22
还是有问题!
改成上面这样之后!有时候起作用,有时候不知道是什么原因!
程序居然停在了!for(index=0;index<nLength;index++)
这个循环里,也就是说! for 有时候居然变成死循环!不知道是哪里的问题!肯定还有问题!
#4
BlueMouse2008-09-23 14:53
该死的瑞星 2009 测试版!
改过之后应该是对的!有时候不成功能原来是该死的瑞星 2009 测试版搞的鬼!真晕呀!
1