Skip to main content

11-4 重載 [] 運算子

現在我們還缺一個重要的功能,那就是存取 Vec 裡的值。

試著執行這段程式看看。

[main.cpp]

#include <iostream>
#include "vec.h"

using namespace std;

int main()
{
    Vec a;

    a.push_back(1);
    cout << "Cap:" << a.capacity() << " Size:" << a.size() << endl;
    a.push_back(3);
    cout << "Cap:" << a.capacity() << " Size:" << a.size() << endl;
    a.push_back(5);
    cout << "Cap:" << a.capacity() << " Size:" << a.size() << endl;
    a.push_back(7);
    cout << "Cap:" << a.capacity() << " Size:" << a.size() << endl;
    a.push_back(9);
    cout << "Cap:" << a.capacity() << " Size:" << a.size() << endl;

    for(int i=0; i<a.size(); i++)
    {
        cout << a[i] << " ";
    }
    cout << endl;

    return 0;
}

我們會得到這個錯誤訊息。

error: no match for 'operator[]' (operand types are 'Vec' and 'int')|

因為在第行中的cout << a[i]