4

C++怎样访问私有成员函数

 3 years ago
source link: https://blog.csdn.net/qq_46423166/article/details/112414351
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

我知道的大概是三种方法:

  1. 通过地址进行访问
  2. 通过友元函数
  3. 通过友元类

第二种和第三种是比较常见的做法,第一种可能不太常见

一,通过地址进行访问

这种方法能够使用只要是因为类的保存机制,类内只有成员变量和虚函数,所以可以利用地址来进行访问。

A a;
*((int*)&a); 来实现

首先将a的地址取出来,然后转化为int型的地址,最后再用解引用为值:

二,通过友元函数

将函数声明为类的友元,那么类就会将函数当作自己人,然后就可以直接访问类的私有成员变量

三,通过友元类

同上面一样,也是将声明为类的友元,然后友元类就能够访问类的私有成员变量


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK