1、友元函数:
#include <iostream>
using namespace std;
class CTest
{
public:
CTest(void){}
virtual ~CTest(void){}
public:
friend void Func(CTest t);
private:
void Display(void){cout<<m_nData<<endl;}
private:
int m_nData;
};
void Func(CTest t)
{
t.m_nData = 6;
t.Display();
}
void main(void)
{
CTest t;
Func(t);
}
2、友元对象
#include <iostream>
using namespace std;
class CStudent;
class CTeacher
{
public:
void SetValue(const CStudent &student);
int GetValue(void);
private:
int m_nMemberData;
};
class CStudent
{
public:
CStudent(const int &nMemberData){m_nMemberData = nMemberData;}
public:
friend class CTeacher;
private:
int m_nMemberData;
};
void CTeacher::SetValue(const CStudent &student)
{
m_nMemberData = student.m_nMemberData;
}
int CTeacher::GetValue()
{
return m_nMemberData;
}
void main(void)
{
CTeacher teacher;
CStudent student(11);
teacher.SetValue(student);
cout<<teacher.GetValue()<<endl;
}
3、友元类
方法一:
#include <iostream>
using namespace std;
class CTest;
class CTest1
{
public:
CTest1(int nData){m_nData = nData;}
virtual ~CTest1(void){}
public:
friend CTest;
private:
int m_nData;
};
class CTest
{
public:
CTest(void){}
virtual ~CTest(void){}
public:
void Func(CTest1 t){cout<<t.m_nData<<endl;}
};
void main(void)
{
CTest test;
CTest1 test1(27);
test.Func(test1);
}
方法二:
#include <iostream>
using namespace std;
class CTest1;
class CTest
{
public:
CTest(void){}
virtual ~CTest(void){}
public:
void Func(CTest1 *pTest1);
};
class CTest1
{
public:
CTest1(int nData){m_nData = nData;}
virtual ~CTest1(void){}
public:
friend CTest;
private:
int m_nData;
};
void CTest::Func(CTest1 *pTest1)
{
cout<<pTest1->m_nData<<endl;
}
void main(void)
{
CTest test;
CTest1 test1(27);
test.Func(&test1);
}
4、嵌套友元
#include <iostream>
using namespace std;
class CLevel1
{
public:
CLevel1(int nData);
virtual ~CLevel1(void);
public:
class CLevel2
{
public:
CLevel2(void);
virtual ~CLevel2(void);
public:
void Func(CLevel1 level1);
};
public:
friend CLevel1::CLevel2;
private:
int m_nData;
};
CLevel1::CLevel1(int nData) : m_nData(nData)
{
}
CLevel1::~CLevel1()
{
}
CLevel1::CLevel2::CLevel2()
{
}
CLevel1::CLevel2::~CLevel2()
{
}
void CLevel1::CLevel2::Func(CLevel1 level1)
{
cout<<level1.m_nData<<endl;
}
void main(void)
{
CLevel1 level1(100);
CLevel1::CLevel2 level2;
level2.Func(level1);
}