一句话总结:要想访问我的保护信息,必须存在于我的Friend列表中。注意头文件不要相互包含
友元类:
// CFriend.hpp
// CppProduct
//
// Created by zhaojunyan on 17/6/17.
// Copyright © 2017年 zhaojunyan. All rights reserved.
//
#ifndef CFriend_hpp
#define CFriend_hpp
#include <stdio.h>
class CPerson;
//CPerson并不在CFriend友元名单里,无法直接访问CFriend的保护信息
class CFriend
{
public:
CFriend();
~CFriend();
int getPersonSalary(CPerson &Person);
};
#endif /* CFriend_hpp */
// CFriend.cpp
// CppProduct
//
// Created by zhaojunyan on 17/6/17.
// Copyright © 2017年 zhaojunyan. All rights reserved.
//
#include "CFriend.hpp"
#include <iostream>
CFriend::CFriend()
{}
CFriend::~CFriend()
{}
int CFriend::getPersonSalary(CPerson &Person)
{
int salary = Person.m_salary;
std::cout<<"salary: "<<salary<<std::endl;
return salary;
}
// CPerson.hpp
// CppProduct
//
// Created by zhaojunyan on 17/6/17.
// Copyright © 2017年 zhaojunyan. All rights reserved.
//
#ifndef CPerson_hpp
#define CPerson_hpp
#include <stdio.h>
#include <stdio.h>
//#include "CFriend.hpp"
class CPerson
{
public:
CPerson(int age, int level, int salary);
~CPerson();
int getAge();
public:
int m_age;
friend class CFriend; //友元类,若想访问我的保护信息,需存在于我的友元名单里
protected:
int m_level;
private:
int m_salary;
};
#endif /* CPerson_hpp */
// CPerson.cpp
// CppProduct
//
// Created by zhaojunyan on 17/6/17.
// Copyright © 2017年 zhaojunyan. All rights reserved.
//
#include "CPerson.hpp"
//初始化列表仅与定义顺序有关
CPerson::CPerson(int age, int level, int salary):m_age(age),m_level(level),m_salary(salary)
{}
CPerson::~CPerson()
{}
int CPerson::getAge()
{
return m_age;
}
// main.cpp
// CppProduct
//
// Created by zhaojunyan on 17/6/17.
// Copyright © 2017年 zhaojunyan. All rights reserved.
//
#include <iostream>
#include "CFriend.hpp"
#include "CPerson.hpp"
using namespace std;
int main(int argc, const char * argv[]) {
// insert code here...
CPerson Person(23,4,10000);
CFriend Friend;
Friend.getPersonSalary(Person);
return 0;
}
友元函数:
//getPersonSalary(CPerson &Person)仅在CFriend.hpp声明,实现在CPerson.cpp
// CPerson.hpp
// CppProduct
//
// Created by zhaojunyan on 17/6/17.
// Copyright © 2017年 zhaojunyan. All rights reserved.
//
#ifndef CPerson_hpp
#define CPerson_hpp
#include <stdio.h>
#include "CFriend.hpp"
class CPerson
{
friend int CFriend::getPersonSalary(CPerson &Person);//友元成员函数
public:
CPerson(int age, int level, int salary);
~CPerson();
int getAge();
public:
int m_age;
//friend class CFriend; //友元类
protected:
int m_level;
private:
int m_salary;
};
#endif /* CPerson_hpp */
// CPerson.cpp
// CppProduct
//
// Created by zhaojunyan on 17/6/17.
// Copyright © 2017年 zhaojunyan. All rights reserved.
//
#include "CPerson.hpp"
#include <iostream>
//初始化列表仅与定义顺序有关
CPerson::CPerson(int age, int level, int salary):m_age(age),m_level(level),m_salary(salary)
{}
CPerson::~CPerson()
{}
int CPerson::getAge()
{
return m_age;
}
int CFriend::getPersonSalary(CPerson &Person)
{
//int salary = Person.m_salary;
int salary = Person.m_salary;
std::cout<<"salary: "<<salary<<std::endl;
return salary;
}