C++ 指向数据成员的指针

问题描述 投票:0回答:1

我对一件事感兴趣 - 在 C++ 中,我们有指向数据成员的指针,例如:

struct A
{
  int a_1 = 1;
};

A a;
int A::* p_a = &A::a_1;
    
a.*p_a = 10;

但是如果我有这样的东西:

struct B
{
  int b_1 = 11;
};

struct A
{
  int a_1 = 1;
  
  B b;
};

类型 B 的对象存储在类型 A 的对象中 - 有没有办法拥有指向嵌套对象的数据成员的指针,即类似这样的:

A a;
/*???*/ p_b = &A::B::b_1;

a.*p_b = 10; // after that - a.b.b_1 is equals to 10

希望我说清楚了:)

c++ pointers pointer-to-member
1个回答
0
投票

可以,你只需要声明你的B变量,然后你就可以引用你嵌套的A变量。例如,我们可以将指针保存在它自己的变量中,然后使用该指针引用 A:

#include <iostream>
using namespace std;

struct A {
    int val = 1;
};

struct B {
    A aWithinB;
};

int main(){
    B myB;

    //pointer to the A held by B
    A *a_ptr = &myB.aWithinB;

    //print val from the nested A using the pointer
    cout << "Val = " << a_ptr->val << endl;
}

输出:

Val = 1
© www.soinside.com 2019 - 2024. All rights reserved.