我想重載加號來連接兩個字符串,但我不斷收到錯誤。C++字符數組連接
VS 2010給出了一個斷言失敗消息: 「表達式:(L 」緩衝區太小「 & & 0)」; 文件: f:\ dd \ vctools \ crt_bld \ self_x86 \ crt \ 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]='\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;
}
它現在工作!謝謝大家!
爲什麼將result.buf中的第一個字符設置爲空字符? strcat_s可能認爲這是緩衝區的末尾。 – Alex
,因爲strcat_s在串的末尾找到'\ 0'。 – Cristi
此問題已被編輯,以包括被接受的答案提出的修正。這使得答案有些沒有意義。這對未來的讀者有什麼用處? – jogojapan