黑客网站推荐无锡网站建设优化公司
目录
1, 全局函数做友元
2, 类做友元
3, 成员函数做友元
友元可以让函数、成员函数、类, 访问另外一个类的私有变量
1, 全局函数做友元
在类中, 通过friend 数据类型 函数名()方式,将函数当着类的友元, 全局函数就可访问类的私有属性
#include <iostream>
#include <string>using namespace std;class Person
{//通过friend修饰全局函数为友元, 可通过test函数访问Person类的私有属性friend void test();public:Person(int age):m_age(age) {};private:int m_age;
};void test()
{Person p(10);//因为test已声明为Person类的友元, 所以可以在类外部访问类的私有属性cout << p.m_age << endl;
}int main()
{test();system("pause");return 0;
}
2, 类做友元
在类中, 通过friend calss 类名方式,将类作为另外一个类的友元
#include <iostream>
#include <string>using namespace std;class PersonB;class PersonA
{
public:void func(PersonB b1);
};class PersonB
{//声明A类是B类的友元friend class PersonA;
public:PersonB(int age) :m_age(age) {}
private:int m_age;
};//注意, 若要使用类B, 必须先定义, 不然不能使用
void PersonA::func(PersonB b1)
{cout << b1.m_age << endl;
}void test()
{PersonA a;PersonB b(10);a.func(b);
}int main()
{test();system("pause");return 0;
}
3, 成员函数做友元
通过friend 数据类型 类::成员函数(), 可声明一个类的成员函数是另外一个类的友元
#include <iostream>
#include <string>using namespace std;class PersonB;class PersonA
{
public:void func();
};class PersonB
{//声明类A的func函数是B类的友元friend void PersonA::func();
public:PersonB(int age) :m_age(age) {}
private:int m_age;
};//注意, 若要使用类B, 必须先定义, 不然不能使用
void PersonA::func()
{PersonB b1(10);cout << b1.m_age << endl;
}void test()
{PersonA a;a.func();
}int main()
{test();system("pause");return 0;
}
说明:若要在一个类中, 使用其他类,那么其他类必须要先定义