我试图在C ++中实现字符串类,
#ifndef STRING
# define STRING
class String{
private:
char *Buffer = new char;
inline unsigned long Length(const char *);
inline unsigned long Length(char *);
inline unsigned long Length(String);
inline unsigned long Length(String *);
public:
~String(void){
delete Buffer;
}
unsigned long Size = 0;
void Equal(const char *);
void Equal(char *);
void Equal(String *);
void Equal(String);
char *Get(void);
//Something is wrong in Add method.
char *Add(const char *);
char *Add(char *);
char *Add(String *);
char *Add(String);
//Something is wrong in Add method
char *Multiply(unsigned long *);
char *Multiply(unsigned long);
char& operator[](const unsigned long Index);
const char& operator[](const unsigned long Index) const;
};
# include "StringIO.hpp"
#endif
StringIO.hpp:
#ifndef STRINGIO
# define STRINGIO
inline unsigned long String::Length(String S){return S.Size;}
inline unsigned long String::Length(String *S){return S->Size;}
void String::Equal(String S){this->Equal(S.Buffer);}
void String::Equal(String *S){this->Equal(S->Buffer);}
inline unsigned long String::Length(const char *S){
unsigned long Count = 0; while(S[Count] != '\0'){ Count++;} return Count;
}
inline unsigned long String::Length(char *S){
unsigned long Count = 0; while(S[Count] != '\0'){ Count++;} return Count;
}
void String::Equal(const char *S){
unsigned long Count = 0; while(Count <= this->Length(S)){
this->Buffer[Count] = S[Count];
Count++;
} this->Size = Count - 1;
}
void String::Equal(char *S){
unsigned long Count = 0; while(Count <= this->Length(S)){
this->Buffer[Count] = S[Count];
Count++;
} this->Size = Count - 1;
}
char *String::Get(void){ return this->Buffer;}
/*Something is wrong in here*/
char *String::Add(String *S){return Add(S->Buffer);}
char *String::Add(String S){return Add(S.Buffer);}
char *String::Add(const char *S){
char *Copy = this->Get(); for(unsigned long Count = 0; Count <= Length(S); Count++){
Copy[this->Size + Count] = S[Count];
} return Copy;
}
char *String::Add(char *S){
char *Copy = this->Get(); for(unsigned long Count = 0; Count <= Length(S); Count++){
Copy[this->Size + Count] = S[Count];
} return Copy;
}
/*Something is wrong in here*/
#endif
我编写了一个添加字符串的方法,以及一个使用此方法添加字符串并将其打印到屏幕的简单程序:
int main(void){
String *X = new String;
String *Y = new String;
X->Equal("Hello world!\n");
Y->Equal("Hello world!\n");
std::cout << X->Add(Y);
delete X; delete Y; //The line giving crash
return 0;
没有编译错误但是当我运行它时,它会给出核心转储错误。我怎么解决它?怜悯,我是C ++的初学者。
编辑:
没问题。
答案 0 :(得分:3)
首先,使用以下命令分配字符串缓冲区:
char *Buffer = new char;
但是这只分配一个单个字符,如果你想编写字符串类,那么你应该使用:
char *Buffer = new char[size];
以及delete[]
,也应该为您的字符串类分配文本(即字符串文字)。
您的::Add
方法也很奇怪:
char *String::Add(const char *S){
char *Copy = this->Get(); for(unsigned long Count = 0; Count <= Length(S); Count++){
Copy[this->Size + Count] = S[Count];
} return Copy;
}
你在哪里为新字符串分配额外的内存?