【问题标题】:Overload operator[] for Char assignment - C++重载运算符 [] 用于 Char 赋值 - C++
【发布时间】:2013-11-30 20:22:03
【问题描述】:

虽然我确实有一些编程经验,但我对 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&amp; operator[](size_t&amp;); 有效

【问题讨论】:

标签: c++ operator-overloading char-pointer


【解决方案1】:

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

#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 是无符号的,因为负索引永远不会是好的。

【讨论】:

    【解决方案2】:

    本文是 C++ 中运算符重载的权威指南(老实说,它主要是语法糖的样板代码)。它解释了所有可能的情况: Operator overloading

    这是您感兴趣的部分:

    class X {
            value_type& operator[](index_type idx);
      const value_type& operator[](index_type idx) const;
      // ...
    };
    

    是的,这是可能的,对于许多 STL 容器(例如 vector),允许数组下标表示法访问数据。

    所以你可以按照以下方式做一些事情:

    char & operator[]( size_t i )
    {
        return *(str + i);
    }
    

    【讨论】:

      【解决方案3】:

      您应该将operator[] 重载为非const 方法并从中返回引用

      char& operator[](const int&);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-30
        • 2016-08-30
        • 1970-01-01
        • 1970-01-01
        • 2020-07-01
        • 2018-12-27
        • 2012-04-22
        • 2015-06-01
        相关资源
        最近更新 更多