将类对象用作数组的索引时会发生什么情况

what happens when a class object is used as an index for an array?

本文关键字:什么情况 索引 对象 数组      更新时间:2023-10-16

假设我们有一个类:

class A {
  private:
      int index;
  public:
  // related overloaded functions and other stuffs
};

现在假设我们将其用作期望 int 的数组中的索引。

A in;
Z z = arr[in]; // arr is of some type Z.

我想问一下当"in"在"中使用时,调用了哪些函数(例如复制构造函数或重载赋值运算符)或在此处直接类型转换对象。

如果类是这样的,会有什么区别

class A {
  private:
    int index1;
    int index2;
  public:
 // related overloaded functions and other stuffs
};

您的A类必须定义operator intoperator size_t。该运算符用于将该类的实例转换为整型类型,此时将进行常规数组访问。例:

class A {
public:
    operator int() const;
};
class IN {
public:
};
int main()
{
    A a;
    IN in[4];
    in[a];
}
相关文章: