022普通函数做类友元函数
#include<iostream>
#include<cstdlib>
#include<string>
#include<vector>
using namespace std;
class Human
{
private:
int age;
string name;
public:
Human();
Human(int age, string name);
~Human()
{
cout << "Human析构函数" << endl;
}
friend void myFriendFunction01(const Human&temHuman) ;
};
void myFriendFunction01(const Human&temHuman)
{
cout << "我是Human类的友元函数" << endl;
cout << temHuman.age << endl;
}
Human::Human()
{
cout << "Human默认构造函数" << endl;
}
Human::Human(int age, string name)
{
this->age = age;
this->name = name;
}
int main(void)
{
Human h1 = Human(12, "jisuanji");
myFriendFunction01(h1);
system("pause");
return 0;
}
023友元类
#include<iostream>
#include<cstdlib>
#include<string>
#include<vector>
using namespace std;
class A
{
private:
int number;
public:
A(int number)
{
this->number = number;
}
friend class B;
};
class B
{
private:
int number02=0;
public:
void myFunction01(const A&temA);
};
void B::myFunction01(const A&temA)
{
cout << "可以访问类A的私有成员" << endl;
cout << temA.number << endl;
}
int main(void)
{
A a(12);
B b;
b.myFunction01(a);
system("pause");
return 0;
}
024友元成员函数
#include<iostream>
#include<cstdlib>
#include<string>
#include<vector>
class A;
class C
{
private:
int number03;
public:
void myFunctionC(int x, A&a);
public:
};
using namespace std;
class A
{
friend class B;
friend void C::myFunctionC(int x, A& a);
private:
int number;
public:
A(int number)
{
this->number = number;
}
};
class B
{
private:
int number02 = 0;
public:
void myFunction01(const A&temA);
};
void C::myFunctionC(int x, A& a)
{
a.number = x;
cout << a.number << endl;
}
void B::myFunction01(const A&temA)
{
cout << "可以访问类A的私有成员" << endl;
cout << temA.number << endl;
}
int main(void)
{
A a(12);
C c;
c.myFunctionC(1, a);
system("pause");
return 0;
}