【发布时间】:2018-05-03 21:02:15
【问题描述】:
我不知道如何重载方括号运算符“[]”,它既可以输入也可以输出,这意味着我将能够:
_class ppp;
ppp[{1,2}] = 1;
char x = ppp[{1,2}] ;
我看到了this question,它给出了这个代码:
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}] ;
******************编辑前******************************
我正在尝试将平方运算符 [] 覆盖为输入和输出信息。而方括号的输入是一个结构体。
我在this question的启发下尝试了这个:
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.但我只是问一些不是硬件主要部分的东西,我也在研究这个小东西一段时间......
【问题讨论】:
-
不清楚您在更改
operator[]s 后如何更改main或非const更改后的样子。 -
如果您只更改一个运算符以接受
int,那么如果您提供int作为参数,将选择重载也就不足为奇了。如果所有其他条件都相同,非const实例将更喜欢非const重载,但如果const重载是唯一可以绑定到您传递的参数的实例,则它不适用。 -
char&你不能返回对局部变量的引用! -
不,这是正确的做法。您只需要返回对某个非局部变量的引用。如果这不可能,请返回一个不同的类,并重载
=。 -
这是意料之中的。如果使用它的对象是
const,则将调用第一个重载。
标签: c++ operator-overloading square-bracket