c++ - 为 Char 赋值重载 operator[] - C++

标签 c++ operator-overloading char-pointer

虽然我确实有一些编程经验,但我是 C++ 的新手。我构建了一个 Text 类,它使用动态 char* 作为主要成员。 类定义如下。

#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&); 有效

最佳答案

您需要提供对角色的引用。

#include <iostream>

struct Foo {
   char m_array[64];
   char& operator[](size_t index) { return m_array[index]; }
   char operator[](size_t index) const { return m_array[index]; }
};

int main() {
    Foo foo;
    foo[0] = 'H';
    foo[1] = 'i';
    foo[2] = 0;
    std::cout << foo[0] << ", " << foo.m_array << '\n';
    return 0;
}

http://ideone.com/srBurV

请注意,size_t 是无符号的,因为负索引永远都不好。

关于c++ - 为 Char 赋值重载 operator[] - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20305216/

相关文章:

C - 将包含 '\0' 的 char 数组复制到另一个 char 数组,消除 '\0'

c++ - 如何将从后台缓冲区获取的像素数据绘制回自身?

c++ - 如何在 map 和 unordered_map 之间进行选择?

C++ 异常处理和内存的动态分配

C++从左向右重载[]

c - 冒泡排序到 char 指针

c++ - C++中的动态数组分配问题

c++ - 为什么我的重载运算符返回零?

c++ - ostream 运算符重载 - 继承

c++ - 用 ofstream 写数据崩溃 C++