一:问题
1 提问:如何在一个类B的对象中访问一个类A的私有成员?
2 回答:在类A中设置友元类B 且 类B中有一个成员的类型是A
二: 代码
#include<iostream>
#include<windows.h>
class Player{
private :
int m_id;
int m_cardnumber;
friend class Cardnumber;//定义友元类B:Cardnumber(也可以定义成public成员)
public :
Player (int id = 101, int cardnumber =10){
m_id = id;
m_cardnumber = cardnumber;
}
void show_cardnubmer(){
std::cout<<m_cardnumber<<"\n";
}
};
class Cardnumber{
private :
Player * m_player;
public :
Player * get_player()
{
return m_player;
}
Cardnumber(){
m_player = new Player();
}
void change_cardnumber(int cardnumber){
m_player->m_cardnumber = cardnumber;//在友元函数change_cardnumber中可以访问类Player中的私有成员m_cardnumber
}
};
void main(){
Cardnumber *cardnumber = new Cardnumber();
cardnumber->get_player()->show_cardnubmer();
cardnumber->change_cardnumber(20);
cardnumber->get_player()->show_cardnubmer();
delete cardnumber;
system("pause");
}