C++ 友元函数
在类的外部是不能访问非公有成员的,而友元允许一个类将对其非公有成员的访问权授予指定的函数或者类。
- 友元:赋予对象具有打破权限的作用。
友元函数
友元函数:用friend修饰的函数,其在类中声明;因为其不属于类成员,因此在类外实现,不需要加限定声明。其赋予友元函数中定义的类的对象打破限定的权限。
#include<iostream>
using namespace std;
class Student{
public:
Student();
Student(string stu,int age)
:name(stu),age(age){
}
friend void printname();
friend void printage(Student stu){
//参数为类的对象
cout<<"我的年龄是: "<<stu.age<<endl;
}
private:
string name;
int age;
};
void printname(){
//友元函数中定义一个对象
Student stu{"小米",23};
cout<<"我的名字是: "<<stu.name<<endl;
}
int main(){
Student stu1{"张三",12};
Student stu2{"李华",24};
printname(); //输出默认初始值
printage(stu1);
printage(stu2);
return 0;
}
2. 友元类****
具体功能和友元函数其实是一致的,友元类的对象只能在类中访问原来的类。不能脱离类
#include<iostream>
using namespace std;
class Student{
public:
Student();
Student(string stu,int age)
:name(stu),age(age){
}
friend class student;
private:
string name;
int age;
};
class student{
public:
student();
//类的组合采用初始化参数列表的方式初始化
student(string name,int age):m_stu(name,age){
}
void print(){
Student stu{"李li华",213};
cout<<stu.name<< " "<<stu.age;
}
private:
Student m_stu;
};
int main(){
student stu{"消费",13};
stu.print();
return 0;
}