在l值和r值的情况下重载下标运算符"[]"

Sea*_*ock 6 c++ operator-overloading subscript-operator

我在我的班级Interval中重载[]运算符以返回分钟.

但我不知道如何使用[]运算符将值分配给分钟.

例如:我可以使用此声明

cout << a[1] << "min and " << a[0] << "sec" << endl;

但是我想重载[]运算符,这样我甚至可以使用分配值来分钟或秒

a[1] = 5;
a[0] = 10;
Run Code Online (Sandbox Code Playgroud)

我的代码:

#include <iostream>

using namespace std;

class Interval
{

public:

    long minutes;
    long seconds;

    Interval(long m, long s)
    {
        minutes = m + s / 60;
        seconds = s % 60;
    }

    void Print() const
    {
        cout << minutes << ':' << seconds << endl;
    }

    long operator[](int index) const
    {
        if(index == 0)
            return seconds;

        return minutes;
    }

};

int main(void)
{
    Interval a(5, 75);
    a.Print();
    cout << endl;

    cout << a[1] << "min and " << a[0] << "sec" << endl;
    cout << endl;

}
Run Code Online (Sandbox Code Playgroud)

我知道我必须将成员变量声明为私有,但为了方便起见,我在此声明为public.

Fre*_*Foo 11

返回对相关成员的引用,而不是其值:

long &operator[](int index)
{
    if (index == 0)
        return seconds;
    else
        return minutes;
}
Run Code Online (Sandbox Code Playgroud)


Vij*_*hew 8

通过删除const并返回引用来更改函数签名:

long& operator[](int index)
Run Code Online (Sandbox Code Playgroud)

现在您将能够编写如下语句:

a[0] = 12;
Run Code Online (Sandbox Code Playgroud)

  • 不要忘记op []的const重载. (7认同)
  • 也就是说,不要删除现有的.*添加*这个. (6认同)

小智 6

重载op []以使用硬编码的"索引"值在这里没有意义,并且您实际上已经在类定义中有了解决方案:

cout << a.minutes << "min and " << a.seconds << "sec" << endl;
Run Code Online (Sandbox Code Playgroud)

您可以将这些转换为方法而不是公共数据成员,这对于不重载op []是无关紧要的.但是,由于您还需要写访问权限,因此方法的唯一优势就是验证(例如,检查0 <=秒<60).

struct Interval {
  int minutes() const { return _minutes; }
  void minutes(int n) { _minutes = n; }  // allows negative values, etc.

  int seconds() const { return _seconds; }
  void seconds(int n) {
    if (0 <= n and n < 60) {
      _seconds = n;
    }
    else {
      throw std::logic_error("invalid seconds value");
    }
  }

  // rest of class definition much like you have it

private:
  int _minutes, _seconds;
};

// ...
cout << a.minutes() << "min and " << a.seconds() << "sec" << endl;
Run Code Online (Sandbox Code Playgroud)

  • @Searock:另一个答案涵盖了它,但我不会推荐它作为解决这个问题的方法. (3认同)