如何输入和输出方括号运算符 []
how to input and output of square bracket operator []
我不知道如何重载方括号运算符"[]",它将输入和输出,这意味着我将能够:
_class ppp;
ppp[{1,2}] = 1;
char x = ppp[{1,2}] ;
我看到了这个问题,它给出了以下代码:
unsigned long operator [](int i) const {return registers[i];}
unsigned long & operator [](int i) {return registers[i];}
这对我不起作用:-(我尝试并做到了:
struct coord {
int x;
int y;
};
class _map
{
public:
struct coord c{3,4};
char operator[](struct coord) const // this is supposed to suppor output
{
cout << "this1" << endl;
return 'x';
}
char& operator[](struct coord) // this is supposed to support input
{
cout << "this2" << endl;
return c.x;
}
void operator= (char enter)
{
cout << enter;
}
};
然后我主要做了:
_map ppp;
ppp[{1,2}] = 1;
char x = ppp[{1,2}] ;
这给了我:
this2
this2
这意味着我无法制作两个差异函数来让我制作两个差异函数,例如:
ppp[{1,2}] = 1;
char x = ppp[{1,2}] ;
******
之前我正在尝试覆盖方形运算符 [] 以输入和输出信息。 而方括号的输入是结构。
我尝试了这个问题的灵感:
struct coord {
int x;
int y;
};
class _map
{
public:
char operator[](struct coord) const // this is supposed to suppor output
{
cout << "this1" << endl;
return 'x';
}
char& operator[](struct coord) // this is supposed to support input
{
cout << "this2" << endl;
char a = 'a';
return a;
}
void operator= (char enter)
{
cout << enter;
}
};
然后我主要做了:
_map ppp;
ppp[{1,2}] = 1;
char x = ppp[{1,2}] ;
这给了我:
this2
this2
当将输入运算符的输入更改为 int 时,一切都很好:
char operator[](int coord) const
{
cout << "this1" << endl;
return 'x';
}
然后我主要做了:
_map ppp;
ppp[{1,2}] = 1;
char x = ppp[2] ;
然后我得到:
this2
this1
这是我的 H.W. 但我只是问一些不是硬件主要部分的东西,我也在做这件事一段时间......
答案全都感谢圣黑猫!
方括号 ("[]"( 的重写函数将返回如下所示的引用:
char& operator[](coord c)
{
return board[c.x][c.y];
}
因此,我们将能够为其分配一个字符,因为它是对某些内存插槽的引用,如下所示:
_map ppp;
ppp[{1,2}] = 1;
另一方面,我们将能够检索内部的内容,因为引用指向一些字符,如下所示:
char x = ppp[{1,2}] ;
这意味着不需要像以前认为的那样使用两个覆盖函数。
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- 如何使用AngelScript注册SFML Vector2运算符
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 布尔比较运算符是如何在C++中工作的
- 重载运算符new[]的行为取决于析构函数
- 如何防止clang格式在流运算符调用之间添加换行符<<