C++操作员重载两次
C++ operator overloading, twice
我正在尝试为明天的考试做一个示例考试,但我遇到了一个小问题,这可能是一个愚蠢的错误。有一个类包含一个包含 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;
}
一个小演示。
#include <iostream>
#include <string.h>
using namespace std;
class String
{
private:
char *data;
int length;
public:
String(const char * str)
{
data = new char[strlen(str)];
strcpy(data, str);
length = strlen(data);
}
char &operator[](int index)
{
//dont forget to check bounds
return data[index];
}
int getLength() const
{
return length;
}
friend ostream & operator << (ostream &out, String &s);
};
ostream &operator << (ostream &out, String &s)
{
for (int i = 0; i < s.getLength(); i++)
out << s[i];
return out;
}
int main()
{
String string("test");
string[1] = 'x';
cout << string;
return 0;
}
相关文章:
- g++的分段错误(在NaN上使用to_string两次时)
- 蛇在C++不会连续转两次
- 检查一个数组是否包含在另一个数组中,以相反的顺序,至少两次
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- 我应该如何去缓解两次出现的cin?
- Realloc 两次无法在 Visual Studio 上运行
- 使用 getline(cin, var) 两次在进行字符串比较时会产生错误 (==)
- 为什么映射插入和 map.find() 的单次迭代比插入和 map.find() 的两次单独迭代慢得多
- C++析构函数调用两次,堆栈分配的复合对象
- 为什么参数在构造 std::thread 时移动两次
- Qt插槽调用了两次
- 做 std::用相同的unique_ptr移动两次
- C++两次定义相同的函数会导致错误
- 为什么具有静态存储持续时间的同一内联变量在包含在 VS2017 编译的两个翻译单元中时会构造和销毁两次
- 对于优化级别为 0 的 std::vector,析构函数被调用两次
- 使用柯南打包时如何避免列出两次依赖?
- 为什么要执行两次位移((x >> 4)<< 4)?
- 是否可以两次实现[]操作员
- 操作员过载两次
- C++操作员重载两次