C ++:使用指向成员的指针访问子结构的数据成员

时间:2018-05-11 23:06:57

标签: c++ pointer-to-member

我需要利用C ++的指向成员的指针功能来使函数访问子结构的成员。请注意,函数必须操作的对象对调用者不可见。

我已将其减少到以下玩具问题(C ++ 14或更高版本):

#include <iostream>

struct SubStruct {
   int c;
};
struct MyStruct {
   int a;
   int b;
   float f;
   SubStruct ss;
};

template <typename Tmember>
auto addTogether(Tmember member) {
    MyStruct s1 = {.a = 1, .b =2, .f =3.3, .ss = {.c = 4}};
    MyStruct s2 = {.a = 10, .b =20, .f =30.0, .ss = {.c = 40}};;

    return s1.*(member) + s2.*(member);
}

int main() {
    std::cout << "sum a = " << addTogether(&MyStruct::a) << std::endl;
    std::cout << "sum b = " << addTogether(&MyStruct::b) << std::endl;
    std::cout << "sum f = " << addTogether(&MyStruct::f) << std::endl;
    //std::cout << "sum c = " << addTogether(&MyStruct::ss::c) << std::endl; //DOES NOT WORK
    //std::cout << "sum c = " << addTogether(&MyStruct::ss.c) << std::endl; //DOES NOT WORK
    return 0;
}

输出符合预期:

sum a = 11
sum b = 22
sum f = 33.3

但是如何将指针传递给数据成员ss.c?请参阅main()中两个注释掉的行。

感谢。

0 个答案:

没有答案