-2
我想要實現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;
有沒有編譯錯誤,但是當我運行它時,它會提供co轉儲錯誤。我該如何解決它?而且要仁慈,我是C++的初學者。
編輯:
沒問題。
您的代碼不執行任何邊界檢查和取消引用可能爲空的指針。我建議1)接受一個比字符串類更加緊張和困難的任務,2)閱讀指針安全和邊界檢查。 –