访问分类符不是万无一失的? [英] Access-specifiers are not foolproof?
问题描述
如果我有类似的类,
class Sample
{
private:
int X;
};
然后我们无法从外部访问X,所以这是非法的,
Then we cannot access X from outside, so this is illegal,
Sample s;
s.X = 10; // error - private access
但是我们可以在强>!我们需要做的是这个,
But we can make it accessible without editing the class! All we need to do is this,
#define private public //note this define!
class Sample
{
private:
int X;
};
//outside code
Sample s;
s.X = 10; //no error!
在ideone工作代码: http://www.ideone.com/FaGpZ
Working code at ideone : http://www.ideone.com/FaGpZ
这意味着,我们可以通过定义宏定义之前或之前#include< headerfile.h>
,
That means, we can change the access-specifiers by defining such macros just before the class definition, or before #include <headerfile.h>
,
#define public private //make public private
//or
#define protected private //make protected private
//or
#define so on
这不是C ++的一个问题(宏/访问限定符/无论什么)?
Isn't it a problem with C++ (Macros/access-specifiers/whatever)?
无论如何,这个主题的观点是:
Anyway, the point of this topic is:
使用宏,我们很容易违反封装。
Using macros, we can easily violate encapsulation. Access-specifiers are not foolproof! Am I right?
推荐答案
但我们可以使它可以访问,而无需编辑类!我们需要做的是这个,
But we can make it accessible without editing the class! All we need to do is this,
从技术上讲,你所展示的是我们可以把法律程序变成未定义的行为不编辑一个特定的类。
Technically, all you've shown is that "we can turn a legal program into Undefined Behavior" without editing one specific class.
这不是新闻。你也可以通过在 main()
:
That's hardly news. You can also turn it into undefined behavior just by adding a line such as this to the end of main()
:
int i = 0;
i = ++i;
C ++中的访问说明符不是安全功能他们不能防范黑客攻击,
Access specifiers in C++ are not a security feature They do not safeguard against hacking attempts, and they do not safeguard against people willfully trying to introduce bugs into you code.
它们只允许编译器帮助保持某些类不变式。它们允许编译器通知您,如果您不小心尝试访问私有成员,就像它是公共的一样。你所展示的是,如果我特别试图打破我的程序,我可以。
They simply allow the compiler to help you maintain certain class invariants. They allow the compiler to inform you if you accidentally try to access a private member as if it were public. All you've shown is that "if I specifically try to break my program, I can". That, hopefully, should be a surprise to absolutely no one.
正如@Gman所说,在C ++语言中重新定义关键字是未定义的行为。它似乎可以在你的编译器上工作,但它不再是一个定义明确的C ++程序,编译器原则上可以做任何喜欢的事情。
As @Gman said, redefining keywords in the C++ language is undefined behavior. It may seem to work on your compiler, but it is no longer a well-defined C++ program, and the compiler could in principle do anything it likes.
这篇关于访问分类符不是万无一失的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!