C++ 如何输入和输出方括号运算符[]
我不知道如何重载方括号运算符“[]”,它将同时输入和输出,这意味着我将能够:C++ 如何输入和输出方括号运算符[],c++,operator-overloading,square-bracket,C++,Operator Overloading,Square Bracket,我不知道如何重载方括号运算符“[]”,它将同时输入和输出,这意味着我将能够: _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];} 这对我不起作用:-(我试过并做到了
_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;
}
};
这给了我:
this2
this2
this2
this2
这意味着我无法创建两个diff功能,这将使我能够创建两个diff功能,例如:
ppp[{1,2}] = 1;
char x = ppp[{1,2}] ;
******************编辑前**************************
我试图将平方运算符[]重写为输入和输出信息。而方括号的输入是一个结构
我的灵感来自:
这给了我:
this2
this2
this2
this2
将输入运算符的输入更改为int时,all是好的:
char operator[](int coord) const
{
cout << "this1" << endl;
return 'x';
}
然后我得到:
this2
this1
这是来自我的H.W.但我只是问一些不是硬件主要部分的东西,我也在做这件小事情一段时间…答案都要感谢HolyBlackCat 方括号(“[]”)的覆盖函数将返回如下引用:
char& operator[](coord c)
{
return board[c.x][c.y];
}
因此,我们将能够为其分配一个char,因为它是对某个内存插槽的引用,如下所示:
_map ppp;
ppp[{1,2}] = 1;
另一方面,我们将能够检索内部内容,因为引用指向某些字符,如下所示:
char x = ppp[{1,2}] ;
这意味着不需要像以前所想的那样使用两个重写函数。不清楚在更改
运算符[]后如何更改main
s或非const
一个运算符在更改后的外观。如果只更改一个运算符以接受int
,那么如果提供int
作为参数,将选择重载也就不足为奇了。非const
实例将更喜欢非const
重载,如果所有其他情况都是这样的话是相等的,但如果const
重载是唯一可以绑定到正在传递它的参数的重载,则它不适用。char&
不能返回对局部变量的引用!不,这是正确的做法。只需返回对某个非局部变量的引用。如果不可能,请返回另一个类with=
重载。这是预期的。如果在其上使用的对象是常量,则将调用第一个重载。
_map ppp;
ppp[{1,2}] = 1;
char x = ppp[{1,2}] ;