友元函数:
在类中用关键词friend修饰的非成员函数(可以是普通函数,也可以是其他类的成员函数)
声明为友元函数后
#include <iostream>
using namespace std;
class A{
private:
int a;
public:
A(int n):a(n){
}
friend void add(A t1,A t2);
};
void add(A t1,A t2)
{
cout<<t1.a + t2.a<<endl;
}
int main()
{
add(A(1),A(2));
return 0;
}
在函数体中可以通过对象名访问类的私有和保护成员
友元成员函数和一般友元函数使用基本相同,只是通过相应的类或对象名来调用
#include <iostream>
using namespace std;
// 声明类 A
class A;
// 声明类 B 和它的 add 函数,用于前向声明
class B {
public:
static void add(A t1, A t2); // 只声明,不定义
};
// 定义类 A,并声明 B::add 为友元
class A {
private:
int a;
public:
A(int n) : a(n) {}
// 声明 B 的 add 函数为友元
friend void B::add(A t1, A t2);
};
// 定义 B 类的 add 函数
void B::add(A t1, A t2) {
cout << t1.a + t2.a << endl; // 这里可以访问 A 的私有成员 a
}
int main() {
B::add(A(1), A(2)); // 正确调用 B 的静态成员函数
return 0;
}
友元类:
若A类为B类的友元函数,则A中的所有成员函数都是B类的友元函数,都可以访问B类的私有和保护成员
class B{
friend class A;}
注意:友元关系不能传递,为单向,不能继承
#include <iostream>
using namespace std;
class A{
private:
int a;
public:
A(int n):a(n){
}
friend class B;
};
class B{
public:
void add(A t1,A t2)
{
cout<<t1.a + t2.a<<endl;
}
};
int main()
{
B t;
t.add(A(1),A(2));
return 0;
}