将类对象用作数组的索引时会发生什么情况
what happens when a class object is used as an index for an array?
假设我们有一个类:
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 int
或operator size_t
。该运算符用于将该类的实例转换为整型类型,此时将进行常规数组访问。例:
class A {
public:
operator int() const;
};
class IN {
public:
};
int main()
{
A a;
IN in[4];
in[a];
}
相关文章:
- 将指针分配给另一个指针时会发生什么情况?
- 在什么情况下,两个堆栈分配的结构对象的 this 点指向同一个地址?
- 在什么情况下,我想在 C/C++ 代码中使用内联汇编代码
- 发生注入类名时会发生什么情况?(C++)
- 在什么情况下,需要共享智能指针而无法使用唯一指针?
- 重新分配向量时,向量中的内存会发生什么情况
- 如果结构中的字符串比使用的 p/调用签名长或短,会发生什么情况?
- 为什么或在什么情况下,你会将参数作为C++中的引用(或指针)传递给函数?
- 如果我向一个12字节的缓冲区写入的字节数少于12,会发生什么情况
- 删除对象(具有不同类型)的引用时会发生什么情况?
- 如果我在 c++ 中以 new 的放置形式使用没有足够的内存,会发生什么情况?
- 使用 Google 基准测试时返回值会发生什么情况?
- 正在连接的等待条件变量的线程会发生什么情况?
- 如果未定义的C++行为符合 C 定义的行为,会发生什么情况?
- 在什么情况下,使用'const T*'输入参数比'const T&'更可取?
- 如果字符串在 C/C++ 中没有 NUL 字符(以防编译器允许它通过)会发生什么情况?
- 将虚拟方法定义为私有方法时会发生什么情况?
- 如果我将"reference to vector"分配给"vector"会发生什么情况
- DirectX:如果绑定索引缓冲区但不绑定顶点缓冲区,会发生什么情况
- 将类对象用作数组的索引时会发生什么情况