c++ 基础知识-类和对象-友元
1.全局函数做友元
#include <iostream>
#include <string>
using namespace std;
class Person
{
friend void test(Person * p);
public:
void fun()
{
m_age = 25;
m_ID = 123;
cout<<"fun()"<<endl;
}
int m_ID;
private:
int m_age;
};
void test(Person * p)
{
cout<<p->m_ID<<endl;
cout<<p->m_age<<endl;
cout<<"test()"<<endl;
}
int main()
{
Person p;
p.fun();
test(&p);
return 0;
}
2.友元类
#include <iostream>
#include <string>
using namespace std;
class Person
{
friend class Student;
public:
Person();
~Person();
public:
int m_age;
private:
int m_ID;
};
Person::Person()
{
this->m_age = 1;
this->m_ID = 123456;
}
Person::~Person()
{
cout<<"Person() : 析构函数"<<endl;
}
class Student
{
public:
Student();
~Student();
void visit();
private:
Person * person;
};
Student::Student()
{
person = new Person;
}
Student::~Student()
{
cout<<"Student() : 析构函数"<<endl;
delete person;
}
void Student::visit()
{
cout<<person->m_age<<endl;
cout<<person->m_ID<<endl;
}
void fun()
{
Student s;
s.visit();
}
int main()
{
fun();
return 0;
}
3.成员函数做友元
注意访问顺序
#include <iostream>
#include <string>
using namespace std;
class Person;
class Student
{
public:
Student();
~Student();
void visit();
private:
Person * person;
};
class Person
{
friend void Student::visit();
public:
Person();
~Person();
public:
int m_age;
private:
int m_ID;
};
Person::Person()
{
this->m_age = 1;
this->m_ID = 123456;
}
Person::~Person()
{
cout<<"Person() : 析构函数"<<endl;
}
Student::Student()
{
person = new Person;
}
Student::~Student()
{
cout<<"Student() : 析构函数"<<endl;
delete person;
}
void Student::visit()
{
cout<<person->m_age<<endl;
cout<<person->m_ID<<endl;
}
void fun()
{
Student s;
s.visit();
}
int main()
{
fun();
return 0;
}