从外部访问类中的私有成员

[复制链接]
发表于 2024-6-21 13:28:12 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
#include <iostream>

template<typename Tag, typename Tag::type M>
struct Rob {
    friend typename Tag::type get(Tag){
        return M;
    }
};
// use
struct A {
    A(int a):a(a){}
private:
    int a;
};
// tag used to access A::a
struct A_f{
    typedef int A::*type;
    friend type get(A_f);
};
template struct Rob<A_f, &A::a>;
int main(){
    A a(42);
    std::cout << "proof:" << a.*get(A_f()) << std::endl;
}

回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表