gpt4 book ai didi

c++ - 如何重载 operator[] 以允许 `object[a] = b` ?

转载 作者:行者123 更新时间:2023-11-27 23:02:33 26 4
gpt4 key购买 nike

可以重载 operator[] 以在括号中接受一个参数。但是,如何重载此运算符以允许用户键入 object[a] = b

最佳答案

您返回对您的项目的引用,例如:

A &operator[](int pos) { return list[pos]; }

所以当你说 object[a]=b; 它实际上被翻译成:

A &tmp=object[a];
tmp=b;

或者更明确地说:

A *tmp=object[a];          // more or less a pointer
*tmp=b; // you replace the value inside the pointer

关于c++ - 如何重载 operator[] 以允许 `object[a] = b` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26317574/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com