我有一個任務,我需要在C++中創建一個自定義的C類型的字符串類。我無法正常工作。目前我的代碼在開始時崩潰,運行時錯誤。我也知道我的許多函數都是錯誤的,但我希望在繼續之前將成員函數進行排序並修復其他函數。請記住,所有的函數原型都給了我們,我不能改變它們。我需要寫出'膽量'這麼說。在C++中創建一個自定義的C類型字符串類
我的構造函數的一開始出了什麼問題?
#include <iostream>
#include "tstr.h"
using namespace std;
//Default constructor to initialize the string to null
TStr::TStr() {
strPtr = 0;
strSize = 0;
}
//constructor; conversion from the char string
TStr::TStr(const char *str) {
int i=0;
while (str[i] != '/0') {
strPtr = new char [strlen(str)+1];
for (i=0; i <strSize;++i) {
strPtr[i] = str[i];
}
++i;
}
strSize = i;
}
//Copy constructor
TStr::TStr(const TStr&) {
}
//Destructor
TStr::~TStr() {
if (strPtr) {
delete[] strPtr;
}
}
//subscript operators-checks for range
char& TStr::operator [] (int i) {
assert (i >= 0 && i < strSize);
return strPtr[i];
}
const char& TStr::operator [] (int i) const {
assert (i >= 0 && i < strSize);
return strPtr[i];
}
//overload the concatenation oprerator
TStr TStr::operator += (const TStr& str) {
//this->strPtr += str.strPtr;
//this->strSize += str.strSize;
return *this;
}
//overload the assignment operator
const TStr& TStr::operator = (const TStr& str) {
if (this != &str) {
delete[] strPtr;
strPtr = new char[strSize = str.strSize];
assert(strPtr);
for (int i=0; i<strSize; ++i) {
strPtr[i] = str.strPtr[i];
}
}
return *this;
}
//overload two relational operators as member functions
bool TStr::operator == (const TStr& str) const {
return (strPtr == str.strPtr && strSize == str.strSize);
}
bool TStr::operator < (const TStr& str) const {
return (strPtr < str.strPtr && strSize < str.strSize);
}
//the length of the string
int TStr::size() {
return strSize;
}
感謝您的任何答覆/幫助! :)
編輯1:好了構造函數現在工作,但我仍然得到一個運行時錯誤,我90%確定它是用我的重載+ =運算符。它看起來很好,但編譯好。我錯過了什麼?
(注:只有小的變化已對上面的代碼做,但讓我知道,如果你想看到一大堆)
//overload the concatenation oprerator
TStr TStr::operator += (const TStr& str) {
for(int i = 0; i < strSize; ++i) {
strPtr[i] += str.strPtr[i];
}
return *this;
}
編輯2:好吧,這是我現在有。編譯得很好,但實際上並沒有將兩個字符串與+ =一起添加,就像它應該一樣。任何人有任何想法?
//overload the concatenation oprerator
TStr TStr::operator += (const TStr& str) {
char *buffer = new char[strSize + str.strSize + 1];
strcpy(buffer, strPtr);
strcat(buffer, str.strPtr);
delete [] strPtr;
strPtr = buffer;
return *this;
}
//overload the assignment operator
const TStr& TStr::operator = (const TStr& str) {
if (this != &str) {
delete[] strPtr;
strPtr = new char[strSize = str.strSize];
assert(strPtr);
for (int i=0; i<strSize; ++i) {
strPtr[i] = str.strPtr[i];
}
}
return *this;
}
我不知道這是否是一個錯字,但它看起來像你的NULL終結符是使用正斜槓而不是轉義字符。 – Dawson
你不需要在析構函數中檢查'if(strPtr)'。 delete []'NULL'指針是一個nop,不會崩潰。 –
另外你可能不應該使用'assert',因爲它在發佈版本中被刪除。使用例外。 –