尽管我确实有一些编程经验,但我对 C++ 还是很陌生。我已经构建了一个使用动态 char* 作为主要成员的Text类。类定义如下。
#include <iostream>
#include <cstring>
using namespace std;
class Text
{
public:
Text();
Text(const char*); // Type cast char* to Text obj
Text(const Text&); // Copy constructor
~Text();
// Overloaded operators
Text& operator=(const Text&);
Text operator+(const Text&) const; // Concat
bool operator==(const Text&) const;
char operator[](const size_t&) const; // Retrieve char at
friend ostream& operator<<(ostream&, const Text&);
void get_input(istream&); // User input
private:
int length;
char* str;
};
我遇到的问题是我不知道如何在传入的operator[]
给定索引处分配char 值。当前的重载运算符 operator[]
用于在提供的索引处返回char。有人有这方面的经验吗?
我希望能够做类似的事情:
int main()
{
Text example = "Batman";
example[2] = 'd';
cout << example << endl;
return 0;
}
任何帮助和/或建议表示赞赏!
提供的解决方案- 非常感谢所有回复
char& operator[](size_t&);
作品