2016-09-29 57 views
0

使用較長版本(something).operator[]()而不是簡單(something)[]的優點是什麼?Operator []長版和短版

例如:

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; 
+1

有真的沒有優勢。儘管你可以使用第二個指針作爲指針:'arr2-> operator [](i)' – Hayt

回答

1

有無。對於用戶定義的類型,[]只是operator[]的語法糖。當您自己定義這些函數時,您只需要使用operator語法。這同樣適用於像operator()operator[]operator newoperator=,所有的運營商......

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 
+0

是的,我最初選擇了33個,只是爲了更容易在程序集中找到它。切換到6 –