c – 数组元素的成员指针

可以定义一个指向成员的指针,并在以后使用:
struct foo
{
  int a;
  int b[2];
};

int main() {
foo bar; int foo::* aptr=&foo::a; bar.a=1; std::cout << bar.*aptr << std::endl; }

现在我需要一个指向数组的特定元素的指针,所以通常我会写
int foo :: * bptr =&(foo :: b [0]);
但是,编译器只是抱怨“无效使用非静态数据成员”foo :: b’“
是否可以这样做(或至少没有工会)?

编辑:我需要指向数组的特定元素的指针,所以int foo :: * ptr指向数组的第二个元素(foo :: b [1]).

一个编辑:我需要通过bar访问数组中的元素* ptr = 2,因为指针在别的地方被使用,所以不能用bar来调用.* ptr [1] = 2或* ptr = 2.

解决方法

问题在于,访问数组中的一个项目是访问一个普通的int的另一个间接级别.如果该数组是一个指针,那么您不会期望能够通过成员指针访问int.
struct foo
{
  int a;
  int *b;
};

int main()
{

  foo bar;
  int foo::* aptr=&(*foo::b); // You can't do this either!
  bar.a=1;
  std::cout << bar.*aptr << std::endl;
}

你可以做的是定义返回你想要的int的成员函数

struct foo
{
  int a;
  int *b;
  int c[2];

  int &GetA() { return a; } // changed to return references so you can modify the values
  int &Getb() { return *b; }
  template <int index>
  int &GetC() { return c[index]; }
};
typedef long &(Test::*IntAccessor)();

void SetValue(foo &f,IntAccessor ptr,int newValue)
{  
    cout << "Value before: " << f.*ptr();
    f.*ptr() = newValue;
    cout << "Value after: " << f.*ptr();
}

int main()
{
  IntAccessor aptr=&foo::GetA;
  IntAccessor bptr=&foo::GetB;
  IntAccessor cptr=&foo::GetC<1>;

  int local;
  foo bar;
  bar.a=1;
  bar.b = &local;
  bar.c[1] = 2;

  SetValue(bar,aptr,2);
  SetValue(bar,bptr,3);
  SetValue(bar,cptr,4);
  SetValue(bar,&foo::GetC<0>,5);
}

那么你至少有一个一致的界面,可以让你改变foo上的不同值.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...