我正在尝试将结构的成员变量与类相关联。这样当我创建一个新类时,我可以在一个结构中指定它与这个成员变量相关联。例如:
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;
}
关于c++ - 是否可以将结构的成员变量作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45805120/