0
明天我想爲我的測試做一個示例考試,但遇到了一個小問題,這可能是一個愚蠢的錯誤。有一個類包含一個char*
,它包含一個C字符串和一個包含該字符串長度的int
。現在我需要做一些類似class[5] = 'd'
的工作。但我不知道如何。我知道我可以重載[]
運算符以返回指向字符串特定字母的指針,但我無法直接指定char
。C++運算符重載,兩次
我的代碼:
#include <iostream>
#include <string>
using namespace std;
class DynString
{
private:
char * _theString;
int _charCount;
public:
DynString(char * theString = nullptr) {
if(theString == nullptr)
_charCount = 0;
else {
_charCount = strlen(theString);
_theString = new char[strlen(theString) + 1]; // +1 null-terminator
strcpy(_theString, theString);
}
}
char* operator[](int index) {
return &_theString[index];
}
DynString operator+(const DynString& theStringTwo) {
DynString conCat(strcat(_theString, theStringTwo._theString));
return conCat;
}
void operator=(const DynString &obj) {
_theString = obj._theString;
_charCount = obj._charCount;
}
friend ostream& operator<< (ostream &stream, const DynString& theString);
friend DynString operator+(char * ptrChar, const DynString& theString);
};
ostream& operator<<(ostream &stream, const DynString& theString)
{
return stream << theString._theString;
}
DynString operator+(char * ptrChar, const DynString& theString) {
char * tempStor = new char[strlen(ptrChar) + theString._charCount + 1] ;// +1 null-terminator
strcat(tempStor, ptrChar);
strcat(tempStor, theString._theString);
DynString conCat(tempStor);
return conCat;
}
int main()
{
DynString stringA("Hello");
DynString stringB(" Worlt");
cout << stringA << stringB << std::endl;
stringB[5] = 'd'; // Problem
DynString stringC = stringA + stringB;
std::cout << stringC << std::endl;
DynString stringD;
stringD = "The" + stringB + " Wide Web";
std::cout << stringD << std::endl;
return 0;
}
讓你的'operator []'返回一個'char&'並相應地改變你的return語句。 –
非常感謝! –
我還建議檢查請求索引是否超過實際字符串的長度,如果有,則拋出異常。 –