[英]How to access elements of an object created using vector
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.所以我正在尝试从课堂上访问“a”。
book[0].a= something;
This doesn't work.这不起作用。 What am I doing wrong?我究竟做错了什么? I am getting runtime error.我收到运行时错误。
You can do book[0].a= something;
你可以做book[0].a= something;
only if lib
becomes a struct
(instead of a class
) or if you make a
public.只有当lib
成为struct
(而不是一class
),或者如果你让a
公众。
You can also create accessors ( int getA() const;
void setA(int);
) and call book[0].setA(something);
您还可以创建访问器( int getA() const;
void setA(int);
)并调用book[0].setA(something);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.