c++ - 为什么我不能用两个参数重载 C++ operator[]?

标签 c++ operator-overloading

<分区>

我知道这行得通:

struct vtx
{
    long  operator[](long line)
    {
        return line;
    }
};

但为什么我不能做类似的事情来模拟两列访问?有什么办法吗?

struct vtx
{
    long  operator[](long line, long column)
    {
        return line + column; //resolved later
    }
};

最佳答案

operator[] 被定义为只接受 1 个参数。接受 2 个参数是不可能的,但你可以接受一个元组:

struct vtx
{
    long  operator[](std::tuple<long, long> loc)
    {
        return std::get<0>(loc) + std::get<1>(loc);
    }
};

// used as foo[std::make_tuple(0, 1)]

关于c++ - 为什么我不能用两个参数重载 C++ operator[]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59104189/

相关文章:

c++ - 连接被拒绝后 connect() 长时间挂起

c++ - 将使用 CreateEvent 和 WaitForMultipleObjects 的程序移植到 Linux

c++ - 无法为 C++ 方法添加性能探针

c++ - std::ostream& operator<<(std::ostream& sstr, const T& val) 的模糊重载

c# - 重载 +=、+、== 和 != 运算符

c++ - 每个操作做两次

python - 在 QGraphicsGridLayout 中调整小部件大小

c++ - 试图重载 << 运算符,但出现错误

c++ - 在一行中连接多个字符串c++

c++ - CString a = "Hello "+ "World!";是否可以?