微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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上的不同值.

原文地址:https://www.jb51.cc/c/114226.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐