Char赋值的重载运算符[]-C++
Overload operator[] for Char assignment - C++
我对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[]
来在传入的给定索引处分配字符值。当前重载运算符operator[]
用于返回所提供索引处的字符。有人有这方面的经验吗?
我希望能够做一些类似的事情:
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++中运算符重载的权威指南(老实说,它主要是语法糖的样板代码)。它解释了一切可能:操作员过载
以下是您感兴趣的部分:
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);
}
您应该将operator[]
重载为非const
方法,并从中返回引用
char& operator[](const int&);
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- 如何使用AngelScript注册SFML Vector2运算符
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 布尔比较运算符是如何在C++中工作的
- 重载运算符new[]的行为取决于析构函数
- 如何防止clang格式在流运算符调用之间添加换行符<<