Char赋值的重载运算符[] - C++

 Seet琸琸 发布于 2023-02-13 16:59

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

#include 
#include 
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[]正在使用返回字符提供的索引.有人有这方面的经验吗?

我希望能够做类似的事情:

int main()
{
  Text example = "Batman";
  example[2] = 'd';

  cout << example << endl;
  return 0;
}

任何帮助和/或建议表示赞赏!

提供解决方案 - 感谢所有回复

char& operator[](size_t&); 作品

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

    2023-02-13 17:01 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有