C ++私人真的私人吗? [英] C++ Is private really private?

查看:244
本文介绍了C ++私人真的私人吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中尝试了 private 访问说明符的有效性。这里:



介面:

  // class_A.h 

class A
{
public:
void printX();
private:
void actualPrintX();
int x;
};实施:

  

code> // class_A.cpp
void A :: printX()
{
actualPrintX();
}

void A :: actualPrintX()
{
std :: cout< x:
}

我建立了一个静态库(.a / .lib )。我们现在有一个class_A.h和classA.a(或classA.lib)对。 我编辑了class_A.h并从中移除了 private:



另一个classTester.cpp:

  #includeclass_A.h//新编辑的标题

int main()
{
A a;

a.x = 12; // G ++和VC ++都允许这个!
a.printX(); // allowed,as expected
a.actualPrintX(); // G ++允许,VC ++给出了未解析的链接器错误

return 0;
}



我知道在篡改图书馆的标题后,所有投注都关闭系统完整性等)虽然方法是hacky,这是真的允许吗?有办法阻止吗?

解决方案

private is 安全机制。这是一种沟通意图和隐藏信息的方式,程序的其他部分不需要知道,从而降低了整体的复杂性。



有两个不同的头文件不符合标准,因此在技术上你进入未定义的行为领域,但实际上,正如你发现的,大多数编译器不会。


I was trying out the validity of private access specifier in C++. Here goes:

Interface:

// class_A.h

class A
{
public:
    void printX();
private:
    void actualPrintX();
    int x;
};

Implementation:

// class_A.cpp
void A::printX()
{
    actualPrintX();
}

void A::actualPrintX()
{
    std::cout << x:
}

I built this in to a static library (.a/.lib). We now have a class_A.h and classA.a (or classA.lib) pair. I edited class_A.h and removed the private: from it.

Now in another classTester.cpp:

#include "class_A.h"    // the newly edited header

int main()
{
    A a;

    a.x = 12;           // both G++ and VC++ allowed this!
    a.printX();         // allowed, as expected
    a.actualPrintX();   // allowed by G++, VC++ gave a unresolved linker error

    return 0;
}

I know that after tampering a library's header all bets are off (I mean, system integrity, etc.) Albeit the method being hacky, is this really allowed? Is there a way to block this? Or am I doing something wrong here?

解决方案

private is not a security mechanism. It's a way of communicating intents and hiding information that other parts of your program do not need to know about, thus reducing overall complexity.

Having two different header files is not standards compliant, so technically you're entering undefined behaviour territory, but practically, as you've found, most compilers won't care.

这篇关于C ++私人真的私人吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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