vector as a private member

Dear all:

I want to put a vector as a private member in a class. In the end is my simple test code.

The code is pretty much the same as one post in this forum:
http://www.cplusplus.com/forum/general/23091/

However, I cannot run my code, in line 29, an error message pops up:
"no match for operator[] (operand types are 'VectorTest' and 'size_t {aka long unsigned int}')".

I cannot figure out why this happens. I commented line 28 and 29 and ran in Debug mode, and I found out that those values 1, 2, 3, 4 are actually not inserted into the vector, but the vector size m_size did increase.

I do not see essential difference between my code and the link above, but that one could run correctly. I have no idea what's wrong with my code.

Any help would be appreciated.

Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <vector>

using std::cout;    using std::endl;    using std::vector;

/*************************************************************************************/
class VectorTest
{
public:
    VectorTest();
    ~VectorTest();
    void vecInsert(int element);
private:
    vector<int> m_vec;
    size_t m_size;     // size of the vector
};

/*************************************************************************************/
int main()
{
    VectorTest myVec;

    myVec.vecInsert(1);
    myVec.vecInsert(2);
    myVec.vecInsert(3);
    myVec.vecInsert(4);

    for (size_t i = 0; i != 4; ++i)
        cout << myVec[i] << " ";

    cout << endl;
    return 0;
}

/*************************************************************************************/
VectorTest::VectorTest() : m_size(0)
{
}

VectorTest::~VectorTest()
{
}

void VectorTest::vecInsert(int element)
{
    m_vec.push_back(element);
    ++m_size;
}
Last edited on
If you want to print the contents of the vector, you could write a member function for that:
1
2
3
4
5
void VectorTest::printElements() const
{
    for (size_t i = 0; i < m_vec.size(); ++i)
        cout << m_vec[i] << ' ';
}

Or you could write a getter function that returns the element at a given index:
1
2
3
4
int VectorTest::getElement(size_t pos) const
{
    return m_vec[pos];
}

or even
1
2
3
4
5
6
7
8
int& VectorTest::operator[](size_t pos)
{
    return m_vec[pos];
}
const int& VectorTest::operator[](size_t pos) const
{
    return m_vec[pos];
}

That last one is what you would need for you to be able to access the elements with the [] operator.
As the compiler is saying, you are trying to use operator[] on your VectorTest class, but you've defined no such operator. Were you expecting it to somehow call the private vector's operator[]? Wouldn't that defeat the point of having it private?
Many thanks to long double main and Zhuge, now I understand the "operator []" part.
Topic archived. No new replies allowed.