当类B需要访问类A中的成员函数或者变量的时候,如果是具有父子关系的类,则可以直接访问,如果不是,则受到作用域的限制,是类B无法直接访问类A中的成员函数或者变量。以下有两种常见的方法实现 :将类A声明为类B中的成员变量。将类B声明为类A的友元类,以下是两种实现。
成员变量
#include "stdafx.h"
#include "iostream"
using namespace std;
class A
{
public:
A(){};
A(int a):m_a(a){}
~A(){}
void Afunc()
{
cout << m_a << endl;
}
public:
int m_a;
};
class B
{
public:
B(){}
B(int b,const A &a):m_b(b),m_clsa(a){}
~B(){}
private:
int m_b;
public:
A m_clsa;
};
int _tmain(int argc, _TCHAR* argv[])
{
A a(10);
B b(100,a);
b.m_clsa.Afunc();
return 0;
}
注意:这种实现方法需要注意类中各成员的权限。
友元类
#include "stdafx.h"
#include "iostream"
using namespace std;
class A
{
public:
A(){};
A(int a):m_a(a){}
~A(){}
void Afunc()
{
cout << m_a << endl;
}
friend class B;
public:
int m_a;
};
class B
{
public:
B(){}
B(int b) :m_b(b){}
~B(){}
void accessm_a(const A &a)
{
cout << a.m_a<< endl;
}
void accessAfunc(A &a)
{
a.Afunc();
}
private:
int m_b;
};
int _tmain(int argc, _TCHAR* argv[])
{
A a(10);
B b(100);
b.accessm_a(a);
b.accessAfunc(a);
return 0;
}
所以综上所述:如果两个不具有父子关系的类需要访问另一个类中的成员时,友元是很优秀的一种选择。注意在调用过程中,类应该以指针或者引用的方式进行传递,避免直接使用值传递,造成的浪费。