友元
關鍵字:friend
#include<iostream>
using namespace std;
class CStu
{
private:
int age;
void fun()
{
age = 12;
cout << age << endl;
}
//將fun1()聲明爲類CStu的一個友元函數,使得fun1()函數可以使用類中的私有成員或者受保護成員
friend void fun1();
};
void fun1()
{
CStu stu;
stu.fun();
}
int main()
{
fun1();
system("pause");
return 0;
}
類內成員對於友元函數相當於public
#include<iostream>
using namespace std;
class CStu
{
protected:
int age;
void fun()
{
age = 12;
cout << age << endl;
}
//將fun1()聲明爲類CStu的一個友元函數,使得fun1()函數可以使用類中的私有成員
friend void fun1();
friend int main();
};
void fun1()
{
CStu stu;
stu.fun();
}
int main()
{
//fun1();
CStu stu1; //main函數中可以使用類內的私有成員函數
stu1.fun();
system("pause");
return 0;
}
友元類
#include<iostream>
using namespace std;
class CStu
{
protected:
int age;
void fun()
{
age = 12;
cout << age << endl;
}
//將fun1()聲明爲類CStu的一個友元函數,使得fun1()函數可以使用類中的私有成員
friend void fun1();
friend int main();
friend class CTeach;
};
class CTeach
{
public:
CStu stu2;
void fun2()
{
stu2.fun();
}
};
void fun1()
{
CStu stu;
stu.fun();
}
int main()
{
//fun1();
//CStu stu1;
//stu1.fun();
CTeach teach;
teach.fun2();
system("pause");
return 0;
}
使用protected成員有兩種方法:繼承和友元
使用private成員:友元
友元的特點:①不受訪問修飾符的影響,即友元函數或者友元類的訪問修飾符可以是public\protected任意一種;
②可以有多個友元。
缺點:破壞類的封裝性,不是迫不得已不使用。
接口函數
#include<iostream>
using namespace std;
class CStu
{
protected:
int age;
void fun()
{
age = 12;
cout << age << endl;
}
//接口函數
public:
int Get()
{
return age;
}
void Set()
{
age = 123;
}
//將fun1()聲明爲類CStu的一個友元函數,使得fun1()函數可以使用類中的私有成員
friend void fun1();
protected:
friend int main();
public:
friend class CTeach;
};
class CTeach
{
public:
CStu stu2;
void fun2()
{
stu2.fun();
}
};
void fun1()
{
CStu stu;
stu.fun();
}
int main()
{
//fun1();
//CStu stu1;
//stu1.fun();
//CTeach teach;
//teach.fun2();
CStu stu1;
stu1.Set();
int a = stu1.Get();
cout << a << endl;
system("pause");
return 0;
}