【问题标题】:what happens when a class object is used as an index for an array?当类对象用作数组的索引时会发生什么?
【发布时间】:2014-12-31 11:03:57
【问题描述】:

假设我们有一个类:

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'什么时候用'in',这里调用了什么函数(比如拷贝构造函数或者重载赋值运算符)或者对象是直接typecast的。

如果类是这样的会有什么不同

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

【问题讨论】:

  • 请贴出A的完整定义。它可能有一个整数类型的转换运算符吗?
  • no 我没有做任何转换操作。只是赋值运算符和复制构造函数。我什至不知道转换运算符。
  • 如果没有转换运算符,这甚至不应该编译,如果您有编译示例,请将其发布为sscce.org

标签: c++ arrays class operator-overloading


【解决方案1】:

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

class A {

public:

    operator int() const;
};

class IN {

public:

};

int main()
{
    A a;

    IN in[4];

    in[a];
}

【讨论】:

  • 谢谢山姆,这正是我想要的。我不知道重载 int()。现在我将测试它谢谢。
猜你喜欢
  • 2022-06-27
  • 1970-01-01
  • 1970-01-01
  • 2016-04-29
  • 2015-09-21
  • 1970-01-01
  • 1970-01-01
  • 2016-11-23
  • 1970-01-01
相关资源
最近更新 更多