private可以防止其他模块进行访问,但如果利用指针,是否可以在其他模块获取到private的数据?
下面对此进行实验:
实验
#include "pch.h" #include <iostream> using namespace std; class A { public: A() { a2 = 3; a3 = 4; } int* fun3() { cout << "a3=" <<a3 << endl; return &a3; } int* fun2() { cout << "a2=" << a2 << endl; return &a2; }
protected: int a2; private: int a3; }; int main() { A itema; int* mytest; mytest = itema.fun3(); cout << "通过指针获取private值a3="<<*mytest << endl; *mytest = 1; cout << "对private值进行修改:"; itema.fun3();
mytest = itema.fun2(); cout << "通过指针获取protected值a3=" << *mytest << endl; *mytest = 1; cout << "对private值进行修改:"; itema.fun2(); return 0; }
|
小结
- private数据外部不能直接获取
- private数据如果把地址传出来,可以在外部进行读取和修改
- protected和private都可以利用指针在外部进行读取和修改
因此private不是万能的,同样可以走后门,进行修改,用同样的方法,我们还可以引出形参指针的地址等;当我们写程序时,也要注意private也可能被外部模块修改。