是否可以将结构的成员变量作为参数传递
Is it possible to pass a struct's member variable as parameter
我正在尝试将结构的成员变量与类相关联。这样当我创建一个新类时,我可以指定它与结构中的这个成员变量相关联。例如:
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
- 新的 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;
}
在联机编译器中检查此代码
你有几个选择。如果你只想要整数(就像你发布的代码一样(,那么只需将整数作为参数传递给构造函数并传递给它正确的数字。
class foo {
public:
foo(int val) {
c = val
}
private:
int c;
};
int main() {
foo f(a[0].b);
}
或者,您可以引用整数。这样,如果一个更改,另一个也将:
class foo {
public:
foo(int &val) : c(val) { } //need to use an initialization list for this one
private:
int &c;
};
int main() {
foo f(a[0].b);
a[0].b = -1; //f.c will be -1 now as well
}
使用 VTT 答案中的数据成员指针是最直接的解决方案,但我经常发现成员指针和成员函数指针语法有点麻烦,我相信编译器很难优化。
对于这类事情,我更喜欢使用无状态的lambda。您可以将 lambda 传递给函数模板,然后编译器可以轻松优化它:
#include <iostream>
struct A {
int a;
int b;
};
static A a[2]{{1, 2}, {3, 4}};
class foo {
public:
int c;
public:
template<typename F>
foo(int index, F getter) { c = getter(a[index]); }
};
int main() {
auto agetter = [](const A& a){ return a.a; };
auto bgetter = [](const A& a){ return a.b; };
foo const f1(0, agetter);
std::cout << f1.c << "n";
foo const f2(0, bgetter);
std::cout << f2.c << "n";
foo const f3(1, agetter);
std::cout << f3.c << "n";
foo const f4(1, bgetter);
std::cout << f4.c << "n";
}
相关文章:
- 如何将指针变量作为引用参数传递?
- 变量模板是否可以作为模板模板参数传递
- 是否可以将结构的成员变量作为参数传递
- C++:访问作为函数参数传递的双指针数组所指向的变量的值
- 在 c++ 模板中将变量作为参数传递
- 是否可以将变量/函数返回作为模板参数传递
- 有什么理由C++ 11+ std::mutex 应该声明为全局变量,而不是作为函数参数传递到 std::thread 中
- 如何将变量作为构造函数参数或函数参数传递
- 让宏将迭代参数传递到通过宏变量提供的代码体中
- 即将将引用作为函数中的参数传递以更改参数变量的值
- 是否可以在不为该数组创建变量的情况下将数组作为参数传递到函数中?
- 当将变量作为函数参数传递时,由于隐式铸造而导致的精度丧失
- 如果结构作为递归函数中的参数传递,如何初始化结构的成员变量
- C 11-当我将局部变量作为参数传递到线程中时,它是否安全
- 如果我有一个将指针变量作为输入的函数,有没有办法将函数作为参数传递
- 为什么我无法访问作为参数传递到函数中的基类的受保护成员变量?
- 如何强制转换变量成员以将其作为函数的引用参数传递
- 直接访问成员变量或作为参数传递
- 使用变量参数列表为传递的引用赋值(VS2010中出错)
- 将变量作为模板参数传递