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;
}
|