gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 16:35:34 26 4
gpt4 key购买 nike

虽然我确实有一些编程经验,但我是 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com