违反反封装的一种实现方式:
Jail.h
#ifndef _INCLUDED_JAIL_
#define _INCLUDED_JAIL_
#include <stdio.h>
class Jail
{
private:
void Release() const {
printf("Escape\n");
}
};
#endif
Felon.h
#ifndef _INCLUDED_FELON_
#define _INCLUDED_FELON_
#define private public
#include "Jail.h"
class Felon
{
public:
void BreakOut(Jail *jail) const {
jail->Release(); // 此处在Felon中访问到了Jail的私有函数成员
}
};
#endif
main.cpp
#include "Felon.h"
#include"Jail.h"
int main()
{
Jail j;
Felon f;
f.BreakOut(&j);
return 0;
}
可通过如下方法来对抗上面的反封装方法:
Jail.h
#if !defined(_INCLUDED_JAIL_) && !defined(protected) && !defined(private)
#define _INCLUDED_JAIL_ // 此时从此句开始到本文件结束都是没有定义的,相当于被#if 0 #endif包围了,因此编译都无法通过
#include <stdio.h>
class Jail
{
private:
void Release() const {
printf("Escape\n");
}
};
#endif
Felon.h
#ifndef _INCLUDED_FELON_
#define _INCLUDED_FELON_
#define private public
#include "Jail.h"
class Felon
{
public:
void BreakOut(Jail *jail) const {
jail->Release();
}
};
#endif
main.cpp
#include "Felon.h"
#include"Jail.h"
int main()
{
Jail j; // 此处编译器(vs2017)会提示:未定义标识符"Jail"
Felon f;
f.BreakOut(&j);
return 0;
}
Reference
John Lakos. Large-Scale C++ Software Design, 2014.