[英]Error trying to access a struct type using a pointer to a vector of structs
#include <iostream>
#include <vector>
using namespace std;
struct a_struct { int an_int; };
int main ()
{
vector <vector <a_struct> > the_vec;
vector <a_struct> * p_vs;
p_vs = & the_vec[0];
*(p_vs)[0].an_int=0; //error: 'class __gnu_debug_def::vector<a_struct,
//std::allocator<a_struct> >' has no member named 'an_int'
}
I can't figure out why I'm getting the above compile error. 我无法弄清楚为什么我得到上面的编译错误。
In C++, []
and .
在C ++中,
[]
和.
have higher precedence than *
. 优先级高于
*
。
Your last line 你的最后一行
*(p_vs)[0].an_int=0;
when fully parenthesized, is 当完全括号时,是
*((p_vs[0]).an_int)=0;
Since p_vs
was declared as 由于
p_vs
被声明为
vector <a_struct> * p_vs;
it is as if p_vs
is an array of vector <a_struct>
elements, so p_vs[0]
is a vector<a_struct>
. 就像
p_vs
是vector <a_struct>
元素的数组一样,所以p_vs[0]
是vector<a_struct>
。
And vector<a_struct>
objects indeed do not have a member an_int
. 而
vector<a_struct>
对象确实没有成员an_int
。
Add some parens and you will get what you want. 添加一些parens,你会得到你想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.