我可以在不使用朋友的情况下访问课外的私人成员吗? [英] Can I access private members from outside the class without using friends?

查看:192
本文介绍了我可以在不使用朋友的情况下访问课外的私人成员吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

免责声明



是的,我完全知道我要问的是完全愚蠢的,任何人想在生产代码中尝试这样的事情应该是燃烧和/或喷射。我主要想看看是否可以完成



现在,这是不可能的,有没有办法访问私人类成员在C ++从类外?例如,是否有任何方法可以通过指针偏移来实现这一点?



(朴素和其他非生产就绪技术欢迎)



更新



如评论中所述,我问这个问题是因为我想写一个关于过度封装的博客文章)。我想看看是否有一种方法说使用私有变量不是100%可靠的方式来实现封装,即使在C ++中。最后,我决定更多地关注如何解决这个问题,而不是为什么它是一个问题,所以我没有提出这里提出的一些突出,因为我计划,但我还是留下了一个链接。 / p>

无论如何,如果任何人对它的出现感兴趣,这里是:

如果类包含任何模板成员函数,您可以专门化该成员函数以满足您的需要。即使原始开发者没有想到它。



safe.h

  class safe 
{
int money;

public:
safe()
:money(1000000)
{
}

template< typename T>
void backdoor()
{
//做一些东西。
}
};

main.cpp:

  #include< safe.h> 
#include< iostream>

class key;

模板<>
void safe :: backdoor< key>()
{
//我的专业化。
money - = 100000;
std :: cout<<金钱< \\\
;
}

int main()
{
safe s;
s.backdoor< key>();
s.backdoor< key>();
}

输出:

  900000 
800000


Disclaimer

Yes, I am fully aware that what I am asking about is totally stupid and that anyone who would wish to try such a thing in production code should be fired and/or shot. I'm mainly looking to see if can be done.

Now that that's out of the way, is there any way to access private class members in C++ from outside the class? For example, is there any way to do this with pointer offsets?

(Naive and otherwise non-production-ready techniques welcome)

Update

As noted in the comments, I asked this question because I wanted to write a blog post on over-encapsulation (and how it affects TDD). I wanted to see if there was a way to say "using private variables isn't a 100% reliable way to enforce encapsulation, even in C++." At the end, I decided to focus more on how to solve the problem rather than why it's a problem, so I didn't feature some of the stuff brought up here as prominently as I had planned, but I still left a link.

At any rate, if anyone's interested in how it came out, here it is: Enemies of Test Driven Development part I: encapsulation (I suggest reading it before you decide that I'm crazy).

解决方案

If the class contains any template member functions you can specialize that member function to suit your needs. Even if the original developer didn't think of it.

safe.h

class safe
{
    int money;

public:
    safe()
     : money(1000000)
    {
    }

    template <typename T>
    void backdoor()
    {
        // Do some stuff.
    }
};

main.cpp:

#include <safe.h>
#include <iostream>

class key;

template <>
void safe::backdoor<key>()
{
    // My specialization.
    money -= 100000;
    std::cout << money << "\n";
}

int main()
{
    safe s;
    s.backdoor<key>();
    s.backdoor<key>();
}

Output:

900000
800000

这篇关于我可以在不使用朋友的情况下访问课外的私人成员吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆