【发布时间】:2015-06-17 23:34:26
【问题描述】:
我正在尝试为明天的考试做一个示例考试,但我遇到了一个小问题,这可能是一个愚蠢的错误。有一个类包含一个包含 C 字符串的 char* 和一个包含该字符串长度的 int。现在我需要像class[5] = 'd' 这样工作。但我不知道怎么做。我知道我可以重载[] 运算符以返回指向字符串特定字母的指针,但我不能直接将char 分配给它。
我的代码:
#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&并相应地更改您的退货声明。 -
我还建议检查请求索引不超过实际字符串的长度,如果超过则抛出异常。
标签: c++ operator-overloading overloading