如何输入和输出方括号运算符 []

how to input and output of square bracket operator []

本文关键字:运算符 输出方 何输入 输入      更新时间:2023-10-16

我不知道如何重载方括号运算符"[]",它将输入和输出,这意味着我将能够:

_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}] ;

这意味着不需要像以前认为的那样使用两个覆盖函数。