C char阵列串联

C++ char array concatenation

本文关键字:阵列 char      更新时间:2023-10-16

我试图超载加号以加以连接两个字符串,但我一直遇到错误。

vs 2010给出断言失败消息:"表达式:(l" buffer toom smalte"&& 0);文件: f: dd vctools crt_bld self_x86 crt src src tcscat_s.inl;行: 42。

您认为我的代码有什么问题?

#include "stdafx.h"
class MyString{
    int l;  // the length of the array pointed by buf
    char *buf; //pointer to a char array
public:
        ...
    MyString(char *);
    friend MyString operator+(MyString &,MyString &);
        ...
};
MyString::MyString(char *p)
{
    buf=new char[strlen(p)+1];
    strcpy_s(buf,strlen(p)+1,p);
    l=strlen(p)+1;
}
MyString operator+(const MyString &a,const MyString &b)
{
    MyString result("");
    result.l=a.l+b.l;
    delete[] result.buf;
    result.buf=new char[result.l+1];
    result.buf[0]='';
    strcat_s(result.buf,result.l+1,a.buf);
    strcat_s(result.buf,result.l+1,b.buf);
    return result;
}
int _tmain(int argc, _TCHAR* argv[])
{
    MyString a("hello"),b("world"),c("");
    c=a+b;
    system("pause");
    return 0;
}

现在起作用!谢谢大家!

strcat_s(result->buf,strlen(a.buf),a.buf);
strcat_s(result->buf,strlen(b.buf),b.buf);

strcat_s的第二个参数是目标缓冲区的大小,而不是应附加的字符串大小。因此,您需要将其更改为

strcat_s(result->buf,result->l+1,a.buf);
strcat_s(result->buf,result->l+1,b.buf);

正如其他人所指出的,其余的操作员 实现也被打破了。新的实例,然后按值返回它是胡说八道。只需在堆栈上实例化结果并按值返回。

在运算符 变量" mystring结果"中被声明在堆栈上,随后通过参考返回,这很糟糕。

然后对OP进行了编辑。变量"结果"不再在堆栈上声明,而是在堆上分配。但是,然后有记忆泄漏。

在这里要做的正确的事情是按值返回,并在堆栈上声明" mystring结果"。还要确保您有一个复制构造函数。这是一个事。

您还应该使构造函数采用" const char*"。

应该是 result.buf=new char[result.l+1];允许null字符。