使用较长版本(something).operator[]()
而不仅仅是(something)[]
有什么好处?
例如:
std::array<int, 10> arr1;
std::array<int, 10> arr2;
for(int i = 0; i < arr1.size(); i++)
std::cout << arr1[i] << ' ';
std::cout << std::endl;
for(int i = 0; i < arr2.size(); i++)
std::cout << arr2.operator[](i) << ' ';
std::cout << std::endl;
答案 0 :(得分:1)
没有。 []
只是用户定义类型operator[]
的语法糖。您自己定义这些函数时只需要operator
语法。这适用于所有运营商,例如operator()
,operator[]
,operator new
,operator=
,...
答案 1 :(得分:0)
语法糖
使用g ++ -g -std = gnu ++ 0x ...
编译0000000000400554 <main>:
#include <array>
int main() {
400554: 55 push %rbp
400555: 48 89 e5 mov %rsp,%rbp
400558: 48 83 ec 60 sub $0x60,%rsp
std::array<int, 10> arr1;
std::array<int, 10> arr2;
arr1[6];
40055c: 48 8d 45 d0 lea -0x30(%rbp),%rax
400560: be 06 00 00 00 mov $0x6,%esi
400565: 48 89 c7 mov %rax,%rdi
400568: e8 19 00 00 00 callq 400586 <std::array<int, 10ul>::operator[](unsigned long)>
arr2.operator[](6);
40056d: 48 8d 45 a0 lea -0x60(%rbp),%rax
400571: be 06 00 00 00 mov $0x6,%esi
400576: 48 89 c7 mov %rax,%rdi
400579: e8 08 00 00 00 callq 400586 <std::array<int, 10ul>::operator[](unsigned long)>
40057e: b8 00 00 00 00 mov $0x0,%eax
}
400583: c9 leaveq
400584: c3 retq
400585: 90 nop