我必须在不使用任何C ++字符串函数的情况下创建String类。所需的功能之一是+ =(连接)。当我在visual studio中运行我的代码时,它工作正常,但是当我在linux的终端中运行时,我得到以下结果: * ./a.out'中的错误:munmap_chunk():无效指针:0x00000000004013cd * < /强> 中止(核心倾倒)。
这是我的代码:
String & String::operator+=(const String & s)
{
int tempSize = size + s.size;
char *temp = new char[tempSize];
for(int i = 0; i < tempSize; i++){
if(i < size)
temp[i] = buffer[i];
else
temp[i] = s.buffer[i - size];
}
delete []buffer;
buffer = temp;
size = tempSize;
return *this;
}
有关为什么我在终端中出现此错误的想法,而不是在Windows上的visual studio中?
以下是我的String类的函数:
class String
{
private:
int size;
char *buffer;
public:
String();
String(const String &);
String(const char *);
~String();
int length();
String & operator=(const String &);
String & operator+=(const String &);
char & operator[](unsigned int);
friend bool operator==(const String &, const String &);
friend bool operator<=(const String &, const String &);
friend bool operator<(const String &, const String &);
friend ostream & operator<<(ostream &, const String &);
};
这是测试代码:
String s1;
assert(s1.length() == 0);
String s2("hi");
assert(s2.length() == 2);
String s3(s2);
assert(s3.length() == 2);
assert(s3[0] == 'h');
assert(s3[1] == 'i');
s1 = s2;
assert(s1 == s2);
s3 = "bye";
assert(s3.length() == 3);
assert(s3[0] == 'b');
assert(s3[1] == 'y');
assert(s3[2] == 'e');
s1 += "re";
cout << s1 << endl;
assert(s1 == "hire");
s1 += "d";
assert(!(s1 == "hire"));
cout << "SUCCESS" << endl;