1

当它到达 test2 需要删除 String 对象的删除部分时,它会崩溃。我不确定它为什么会崩溃。它说“调试断言失败!”。我是否删除了动态分配的 char 数组错误?

strdrv.cpp:

#include <iostream>
#include <stdlib.h>
#include "strdrv.h"

int main() {
test2();
return 0;
}
void test2() {
cout << "2. Testing S2: String one arg (char *) constructor."
    << endl << endl;
csis << "2. Testing S2: String one arg (char *) constructor."
    << endl << endl;
String s2("ABC");
s2.print();
wait();
}

字符串.cpp:

#include "String.h"
#include <iostream>

using namespace std;
String::String(char* s) {
int sLength = 0;

for (int i = 0; s[i] != '\0'; i++) {
    sLength++;
}

buf = new char[sLength+1];
dynamicallyAlloc = true;
buf = s;

length = sLength;

/*buf[length] = '\0';*/ 
}

String::~String() {
if(dynamicallyAlloc)
    delete []buf;
}

字符串.h:

#ifndef _STRING_H
#define _STRING_H

#include <iostream>

using namespace std;

class String {
protected:
bool dynamicallyAlloc;
char nullChar;
int length;
char* buf;
void calculateStringLength();


public:
String();
String(char*);
String(char);
String(int);
String(const String&);
String(char, int);
~String();
int getLength() const;
char* getString() const;
String& operator=(const String&);
String& operator=(const char*);
String& operator+=(const String&);
String operator+() const;
char& operator[](int);
String& operator++();
String& operator--();
String operator++(int);
String operator--(int);
String substr(int, int);
void print();
friend String operator+(const String&, const String&);
friend String operator+(const String&, const char*);
friend String operator+(const char*, const String&);
friend String operator+(const String&, char);
friend String operator+(char, const String&);
friend char* operator+(const String&, int);
friend char* operator+(int, const String&);
friend int operator==(const String&, const String&);
friend int operator!=(const String&, const String&);
friend int operator<(const String&, const String&);
friend int operator<=(const String&, const String&);
friend int operator>(const String&, const String&);
friend int operator>=(const String&, const String&);
friend ostream& operator<<(ostream& os, const String& s1);
};

#endif
4

1 回答 1

4

要复制数组内容,不要复制指针,而是

buf = s;

你想复制内容

memcpy(buf,s, sLength+1);

这将保留buf您已分配以供以后删除的内容。

于 2013-07-25T01:57:50.650 回答