加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 数组元素的成员指针

发布时间:2020-12-16 05:37:05 所属栏目:百科 来源:网络整理
导读:可以定义一个指向成员的指针,并在以后使用: 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
可以定义一个指向成员的指针,并在以后使用:
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上的不同值.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读