友元

2017-04-08  本文已影响0人  安然_fc00

1.友元的三种形式

(1).普通的非成员函数被定义为类的友元函数

(2).把其他类的成员函数定义成友元

class Student;
class Teacher
{
private:
    Student* pT;
public:
    void assignGrade(Student& s);   
};

void test(Student&s);

class Student
{
private:
    Teacher *pT;
    int someHours;
    double grade;
public:
    friend void Teacher::assignGrade(Student& s);
    friend void test(Student& s);
};

void test(Student&s){
    int i=s.someHours;
}

(3).友元类

class Student;
class Teacher
{
private:
    Student* pList;
public:
    void assignGrade(Student &s); 
    void adjustHours(Student &s);
};
class Student 
{
private: 
    Teacher*pT; 
    int somesterHours; 
    double grade;
public: 
    friend class Teacher;//在学生类种把教师类声明为友元类 
}; 

2.友元的使用场合

3.友元函数与类成员函数的区别

上一篇下一篇

猜你喜欢

热点阅读