外部的函数,访问类中的私有变量
#include <iostream>
using namespace std;
class Message
{
public:
Message(int a,int b):x(a),y(b){}
friend void showMessage(Message &msg);
private:
int x;
int y;
};
void showMessage(Message &msg)
{
cout<<"a:"<<msg.x<<endl;
cout<<"b:"<<msg.y<<endl;
}
int main()
{
Message msg(1,2);
showMessage(msg);
return 0;
}
A的成员函数,作为B的友元函数,访问B的私有成员
#include <iostream>
using namespace std;
class Message_B;
class Message_A{
public:
void showMessage_B(Message_B &msg_b);
};
class Message_B{
public:
Message_B(int x,int y):a(x),b(y){}
friend void Message_A::showMessage_B(Message_B &msg_b);
private:
int a;
int b;
};
void Message_A::showMessage_B(Message_B &msg_b)
{
cout<<"a:"<<msg_b.a<<endl;
cout<<"b:"<<msg_b.b<<endl;
}
int main()
{
Message_A msg_a;
Message_B msg_b(1,2);
msg_a.showMessage_B(msg_b);
return 0;
}