C++的private的属性或方法真的不能访问吗? no

        我们通常说,C++的private属性或者方法不能被其他的对象访问,在很多时候的确是这样,但不是绝对的,只要你想办法,总有办法可以访问的废话不多说,直接上代码了。

1)访问private的私有成员:

#include <iostream>
using namespace std;

class Parent
{
public:
 virtual void fun()
 {
  cout<<"Parent::fun()"<<endl;
 }
};

class Child:public Parent
{
private:
 virtual void fun()
 {
  cout<<"Child::fun"<<endl;
 }
};

int main(int argc, char** argv)
{
 Parent* ch = new Child;
 ch->fun();//输出Child::fun
 delete ch;
 return 0;
}

        很奇怪吧?其实严格说,C++的禁止外部类访问private 是指在编译期,运行期都是在内存中的数据,是可以做任何修改的。而C++的多态是在编译期间,当在编译期间由于多态的关系,虚函数表中(如果不知道什么是虚函数表可以去看看C++对象的内存模型或在网上搜索资料)子类Child重写的了虚函数fun(),所以在虚函数表的第一个地址就是子类的fun的地址,也就是说用父类对象new一个子类,其父类的对象的指针指向的地址数虚函数表的第一个地址,也就是Child的virtual函数fun()的地址。但是在运行期间时,什么private、public其实都是都不起作用,都是内存中的数据,所以结果就输出Child::fun也就不足为奇了。所以啊,我们不得不说C++博大精深!

1)访问private的私有属性:

#include <iostream>
using namespace std;

class Parent
{
private:
 int number;
 char temp;
 char tmp[50];

扫描二维码关注公众号,回复: 1446832 查看本文章

 
 void show()
 {
  cout<<"private:"<<endl<<temp<<endl<<tmp<<endl<<number<<endl;
 }
public:

 Parent( int c, char a, char b[50]):temp(a), number(c)
 {
  strcpy(this->tmp, b);
 }
};

int main(int argc, char** argv)
{
 Parent pa( 5,'H', "hello world!");
 //pa.show(); //不能访问私有的
 char* p = (char*)&pa;
 cout<<(int)*p<<endl;  //访问私有的,输出5
 cout<<*(p+4)<<endl;   //访问私有的,输出H
 cout<<(p+5)<<endl;   //访问私有的,输出hello world
 return 0;
}

        其实在C/C++的世界里面,指针可以说是无所不能的,非常强大,上面的就一个例子,通过强制类型转换和指针偏移就可以访问private的属性。

以上代码在VS2008上验证通过,其观点仅仅代表个人理解,有不当之处还请多多指教。

 

猜你喜欢

转载自blog.csdn.net/u013421892/article/details/49276935