我正在尝试重载我的类的运算符 new,我想为对象的属性和类中未定义的字符向量分配空间。
但是当我实例化一个新对象时,先前对象的字符正在改变。难道我做错了什么?
class StringData
{
public:
friend class String;
int refCount;
int len;
int maxLen;
~StringData()
{
}
StringData()
{
maxLen = 1000;
len = 0;
refCount = 1;
}
StringData(const char * string)
{
maxLen = 1000;
char * data = buffer();
len = 0;
while (string[len] != '\0' && len < (maxLen - 1))
{
data[len] = string[len];
len++;
}
data[len] = '\0';
refCount = 1;
}
char* buffer()
{
return reinterpret_cast<char*>(this + 12);
}
public:
void* operator new(size_t size, int maxLen)
{
return ::operator new(size + round4(maxLen + 1));
}
static int round4(int len)
{
return ((((int) (len / 4)) + 1) * 4);
}
void operator delete(void* obj)
{
::operator delete(obj);
}
void operator delete(void* obj, int size) throw ()
{
::operator delete(obj);
}
};
我在其他课程中使用它:
class String{
public:
StringData * data;
String(StringData * data){
this->data = data;
}
public:
String(const char*);
String(const String&);
~String();
String& operator =(const String);
String& operator =(const char *);
int length() const;
bool operator ==(const String&) const;
int compare(const String&) const;
bool operator ==(const char*) const;
int compare(const char*) const;
String& operator +(const String&) const;
String operator +(const char*) const;
String operator +=(const String&);
String operator +=(const char*);
String toLower();
String toUpper();
char operator [ ](int) const;
char& operator [ ](int);
void print() const;
};
String::String(const char * string){
int stringLen = 0;
while (string[stringLen] != '\0')
stringLen++;
data = new (stringLen + 1) StringData(string);
}
String::String(const String& string){
data = string.data;
string.data->refCount++;
}
String::~String(){
this->data->refCount--;
if (this->data->refCount == 0)
delete data;
}
String& String::operator=(const String string){
data->refCount--;
if (this->data->refCount == 0)
delete data;
data = string.data;
string.data->refCount++;
return *this;
}
void String::print() const{
printf("%s\n", data->buffer());
}
我的主要功能是:
int main(){
String *a = new String("boisahzashdacaraverdeepretaeazuleamarelaecinzaevermelha");
a->print();
String * s = new String("freestepehnoisquevoaashashashhasshashhasssasassadasd");
String * b = new String("kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk");
a->print();
s->print();
return 0;
}
当我执行时,字符串被破坏了:
boisahzashdacaraverdeepretaeazuleamarelaecinzaevermelha
boisahzashdacaraverd
无花果