How to access elements of an object created using vector

时间:2015-07-28 14:10:13

标签: c++

I was trying to create objects to a class dynamically using vector.

class lib
{
    int a;
};

THen using this to make objects.

vector<lib> book;
book.resize(n);  //n is the number of objects.

So I am trying this to access 'a' from the class.

book[0].a= something;

This doesn't work. What am I doing wrong? I am getting runtime error.

1 个答案:

答案 0 :(得分:1)

You can do book[0].a= something; only if lib becomes a struct (instead of a class) or if you make a public.

You can also create accessors (int getA() const; void setA(int);) and call book[0].setA(something);