c++ - 是否可以将结构的成员变量作为参数传递

标签 c++

我正在尝试将结构的成员变量与类相关联。这样当我创建一个新类时,我可以在一个结构中指定它与这个成员变量相关联。例如:

struct A {
  int a;
  int b;
};

static A a[2];
a[0].a = 1;
a[0].b = 2;
a[1].a = 3;
a[1].b = 4;

class foo {
 public:
  foo(int index, ???) {
    c = a[index].???;  //Is it possible to define the 2nd parameter as a getter of struct A's member? So this line could resolve to either a[index].a or a[index].b?
  }
 private:
  int c;
};

这样:

  • new foo(0, ???) 将给定的 c 设置为 1 ???引用 A::a
  • new foo(0, ???) 将给定的 c 设置为 2 ???引用 A::b
  • new foo(1, ???) 将给定的 c 设置为 3 ???引用 A::a
  • new foo(1, ???) 将给定的 c 设置为 4 ???引用 A::b

最佳答案

是的,有可能,你需要传递一个数据成员指针:

#include <iostream>

struct A
{
    int a;
    int b;
};

static A a[2]
{
    1, 2
,   3, 4
};

class foo
{
    public: int c;

    public:
    foo(int const index, int A::* const p_field)
    {
        c = a[index].*p_field;
    }
};

int main()
{
    foo const f1(0, &A::a);
    ::std::cout << f1.c << ::std::endl;
    foo const f2(0, &A::b);
    ::std::cout << f2.c << ::std::endl;
    foo const f3(1, &A::a);
    ::std::cout << f3.c << ::std::endl;
    foo const f4(1, &A::b);
    ::std::cout << f4.c << ::std::endl;
    return 0;
}

Check this code at online compiler

关于c++ - 是否可以将结构的成员变量作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45805120/

相关文章:

c++ - 粉碎 C++ VPTR

c++ - 为什么 boost::bind with deleted object 有效?

c++ - 如何在 constexpr 函数中强制出现编译错误,而不是让它衰减到非 constexpr 上下文中?

c++ - 收到有关 _Vector_const_iterator 无法转换为 _Vector_iterator 的错误

c++ - 尽管在任何地方都没有额外的 ']',但语法错误 : ']' was unexpected here,?

c++ - 将 vector<unique_ptr<T>> 转换为 vector<unique_ptr<const T>>

c++ - libc++ 中的短字符串优化机制是什么?

c++ - 使用 GoogleTest 进行复合测试?

c++ - 根据函数签名将引用作为左值/右值传递

c++ - boost interprocess file_lock不适用于多个进程