1.介绍
友元就是让一个函数或一个类访问另一个类的私有成员,关键字friend。
2.代码实现
全局函数做友元:
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
class Person {
friend int main();//全局函数作为Person类的友元
public:
Person() {
this->age = 18;
this->weight = 280;
}
int age;
private:
int weight;
};
int main() {
Person p1;
cout << p1.age << endl;
cout << p1.weight;
}
类做友元:
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
class dog;
class Person {
friend class dog;//dog类作为Person类的友元
public:
Person() {
this->age = 18;
this->weight = 280;
}
int age;
private:
int weight;
};
class dog {
public:
Person* person;
dog() {
person = new Person;
}
void visit();
};
void dog::visit() {
cout << person->age << endl;
cout << person->weight << endl;
}
int main() {
dog d1;
d1.visit();
}
成员函数做友元
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
class dog;
class Person {
friend void dog::visit();
public:
Person() {
this->age = 18;
this->weight = 280;
}
int age;
private:
int weight;
};
class dog {
public:
private:
Person* person;
public:
dog() {
person = new Person;
}
void visit();
void visit1();
};
void dog::visit() {
cout << person->age << endl;
cout << person->weight << endl;
}
void dog::visit1() {
cout << person->age << endl;
cout << person->weight << endl;
}
int main() {
dog d1;
dog d2;
d1.visit();
d2.visit1();
}