【问题标题】:how to input and output of square bracket operator []如何输入和输出方括号运算符[]
【发布时间】: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&amp; 你不能返回对局部变量的引用!
  • 不,这是正确的做法。您只需要返回对某个非局部变量的引用。如果这不可能,请返回一个不同的类,并重载 =
  • 这是意料之中的。如果使用它的对象是const,则将调用第一个重载。

标签: c++ operator-overloading square-bracket


【解决方案1】:

答案全靠HolyBlackCat!

方括号 ("[]") 的覆盖函数将返回如下引用:

char& operator[](coord c)
{
    return board[c.x][c.y];
}

因此,我们可以为它分配一个 char,因为它是对某个内存插槽的引用,如下所示:

_map ppp;
ppp[{1,2}] = 1;

另一方面,我们将能够检索里面的内容,因为引用指向某个字符,如下所示:

char x = ppp[{1,2}] ;

这意味着不需要之前认为的两个覆盖函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-23
    • 2022-11-04
    • 2021-03-30
    • 1970-01-01
    • 2016-01-28
    • 1970-01-01
    相关资源
    最近更新 更多