c++ - 在左值和右值情况下重载下标运算符 "[ ]"

标签 c++ operator-overloading subscript-operator

我在类 Interval 中重载了 [] 运算符以返回分钟

但我不确定如何使用 [] 运算符将值分配给 minutessecond

例如:我可以使用这个语句

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

但我想重载 [] 运算符,这样我什至可以使用 给分钟或秒赋值

a[1] = 5;
a[0] = 10;

我的代码:

#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;

}

我知道我必须将成员变量声明为私有(private)的,但为了方便我在这里声明为公共(public)的。

最佳答案

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

long &operator[](int index)
{
    if (index == 0)
        return seconds;
    else
        return minutes;
}

关于c++ - 在左值和右值情况下重载下标运算符 "[ ]",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3854419/

相关文章:

c++ - 为什么我的右值重载下标运算符没有被调用

c++ - 有没有办法从更简洁的东西中获得 (*pointer)[ index ] 功能?

C++模板题

矩阵的 C++ 重载运算符

c# - VTK r(reset)键代码实现

c++ - 为什么可以将友元函数定义放在类定义中?

c++ - 在 C++ 中重载 Subscript[] 运算符以设置类(量词)的大小。

swift - 在 Swift 中的 CKRecord 上定义下标时发生堆栈溢出

c++ - 二叉树插入指针问题

android - 寻找在Win/Linux/MacOSX/Android/IOS上进行跨平台开发的OpenGL ES框架