C++:重载下标运算符(不同的返回类型)

C++: overloading subscript operator (different return typ)

本文关键字:返回类型 重载 下标 运算符 C++      更新时间:2023-10-16

我知道一个返回值不足以覆盖一个函数(我在stackoverflow上读到了关于它的不同线程),但有没有一种方法可以重载类的下标运算符,只返回值(我不能改为通过引用类型的函数返回)

它必须看起来像或者至少工作起来像:

解决这个问题的最佳方法是什么(必须是操作员)?

更新:问题是,不允许只使用返回类型重载成员或运算符。

struct A {int a; int b; double c;};
struct B {int a; int b; array<double,2> c;};
class Whatever
{
public:
A operator [](unsigned int ) const; //it's just reading the element
B operator [](unsigned int ) const;
}
A operator [](unsigned int Input){
//...
}
B operator [](unsigned int Input){
//...
}

假设您知道要访问哪种类型,那么您可以返回一个代理,该代理可以转换为任何一种类型,并且可能在转换时进行访问。因为您想要访问一个const对象,它应该是相当直接的。当试图对更新界面进行同样的操作时,事情会变得有点混乱:

class Whatever;
class Proxy {
    Whatever const* object;
    int             index;
public:
    Proxy(Whatever const* object, int index)
        : object(object)
        , index(index) {
    }
    operator A() const { return this->object->asA(this->index); }
    operator B() const { return this->object->asB(this->index); }
};
class Whatever {
    // ...
public:
    Proxy operator[](int index) { return Proxy(this, index); }
    A asA(index) { ... }
    B asB(index) { ... }
};

主要的限制是不能直接访问AB的成员:需要先转换为AB。如果这两种类型实际上是已知的,那么可以创建一个Proxy,它适当地转发各自的成员函数。当然,如果有常用的命名成员函数或数据成员,则需要首先显式转换。