C++ 当类对象用作数组的索引时会发生什么情况?
假设我们有一节课:C++ 当类对象用作数组的索引时会发生什么情况?,c++,arrays,class,operator-overloading,C++,Arrays,Class,Operator Overloading,假设我们有一节课: 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”时,调用了哪些函数(比如复制构造函数或重载赋值运算符),或者直接在这里对对象进行类型转换 如果课
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”时,调用了哪些函数(比如复制构造函数或重载赋值运算符),或者直接在这里对对象进行类型转换
如果课堂是这样的,会有什么不同
class A {
private:
int index1;
int index2;
public:
// related overloaded functions and other stuffs
};
您的
A
类必须定义运算符int
或运算符size\t
。该运算符用于将该类的实例转换为整数类型,在该类型上进行常规数组访问。例如:
class A {
public:
operator int() const;
};
class IN {
public:
};
int main()
{
A a;
IN in[4];
in[a];
}
请张贴
A
的完整定义。它可能有一个到整型的转换运算符吗?没有,我没有做任何转换运算符。只需赋值运算符和复制构造函数。我甚至不知道转换运算符。如果没有转换运算符,这甚至不应该编译,如果你有一个编译示例,请将其发布为。谢谢sam,这正是我要找的。我不知道如何重载int()。现在我来测试一下,谢谢。