今天突然遇到这个需求了,就拿出来记录一下。

常用的3种方法

  1. set/get接口
  2. 友元类/友元函数
  3. 通过指针访问内存地址

1.友元方法

#include<iostream>
using namespace std;
class A {
public:
	A(){}
	~A(){}

	friend class B; //声明友元类
private:
	int num = 10;
};

class B {
public:
	A a;
	int Sum(){
		return a.num + 10; 
	}
};
int main(){
	B b;
	cout << b.Sum()<< endl;
}

2. 内存地址操作法


#include <iostream>
#include <string>
using namespace std;
 
class center
{
public:
	void setX(float _x){x=_x;}
	void setY(float _y){y=_y;}
	void setMeanValue(float avg){meanValue=avg;}
	float getX(){return x;}
	float getY(){return y;}
	float getMeanValue(){return meanValue;}
	center():x(0.0),y(0.0),meanValue(0.0){}
private:
	float x;
	float y;
	float meanValue;
};
 
int main()
{
	center A;
	//普通青年的赋值方法;
	A.setX(1.0);
	A.setY(4.0);
	A.setMeanValue(13.0);
	cout<<A.getX()<<" "<<A.getY()<<" "<<A.getMeanValue()<<endl;
	
	//文艺青年的赋值方法;
	//*((float*)&A):将center对象A的内存空间强制类型转化为用int*指向的内存空间,访问该内存
	float tmp = *((float*)&A);
	cout<<tmp<<endl;//输出A.x的值
	tmp = *((float*)&A + 1);
	cout<<tmp<<endl;//输出A.y的值
	*((float*)&A + 2)=2;//修改A.meanValue的值
	cout<<A.getMeanValue()<<endl;
}

也可以通过友元的内存地址来操作,即通过class B 的内存地址访问 class A的私有成员。

转载:
C++访问私有成员变量的方法

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐