可以定义一个指向成员的指针并在以后使用它:
struct foo
{
int a;
int b[2];
};<p></p>
<p>int main()
{<br/>
foo bar;
int foo::* aptr=&foo::a;
bar.a=1;
std::cout << bar.*aptr << std::endl;
}</p>
现在我需要一个指向数组特定元素的指针,所以通常我会写
int foo::* bptr=&(foo::b[0]);
然而,编译器只是提示 "invalid use of non-static data member 'foo::b'
"
是否有可能完全做到这一点(或至少没有 union )?
编辑:我需要一个指向数组特定元素的指针,所以 int foo::* ptr
指向数组的第二个元素( foo::b[1]
).
另一个编辑:我需要通过 bar.*ptr=2
访问数组中的元素,因为指针在其他地方使用,所以它不能'不能用 bar.*ptr[1]=2
或 *ptr=2
调用。
最佳答案
However, the compiler just complains about an "invalid use of non-static data member 'foo::b'"
这是因为foo::a
和foo::b
有不同的类型。更具体地说,foo::b
是一个大小为 2 的 int
数组。您的指针声明必须兼容,即:
int (foo::*aptr)[2]=&foo::b;
Is it possible to do this at all (or at least without unions)?
是的,见下文:
struct foo
{
int a;
int b[2];
};
int main()
{
foo bar;
int (foo::*aptr)[2]=&foo::b;
/* this is a plain int pointer */
int *bptr=&((bar.*aptr)[1]);
bar.a=1;
bar.b[0] = 2;
bar.b[1] = 11;
std::cout << (bar.*aptr)[1] << std::endl;
std::cout << *bptr << std::endl;
}
根据 OP 的要求更新了帖子。
关于c++ - 指向数组元素的成员指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/674635/