C++中的友元函数和友元类

友元函数可以修改类的私有属性,写在类的public/private/protected底下都可以。友元函数的函数体写在类的外面时,写法和普通函数一样,不需要加friend关键字,但函数入口参数里面一般肯定是要带一个类的指针或者类的引用以便使用类的私有属性。

友元类的作用和友元函数相同。当一个类A被声明为另外一个类B的友元类时,则类A可以访问类B的私有属性。类A中的函数入口参数一般都要带有类B的指针或类B的引用。

例如:

  1 //.h文件
  2 #pragma once
  3 class myteacher
  4 {
  5 public:
  6     myteacher(void);//无参构造函数
  7     myteacher::myteacher(int a,const char* n);//有参构造函数
  8     myteacher(const myteacher&);//拷贝构造函数
  9     ~myteacher(void);
 10     void printT(void);
 11     friend void modifyT(myteacher&,int,const char*);
 12     friend class mystudent;//mystudent是myteacher的友元类,可以访问myteacher中的私有属性
 13 
 14 private:
 15     int age;
 16     char name[32];
 17 };
 18 
 19 
 20 class mystudent
 21 {
 22 public:
 23     mystudent(int s);
 24     void printT(myteacher&);
 25 
 26 private:
 27     int score;
 28 };
 29 
 30 
 31 
 32 //.cpp文件
 33 #include "myteacher.h"
 34 #include <string.h>
 35 #include <iostream>
 36 
 37 //无参构造函数
 38 myteacher::myteacher(void)
 39 {
 40     age=18;
 41     strcpy(name,"Li");
 42 }
 43 
 44 //有参构造函数
 45 myteacher::myteacher(int a,const char* n)
 46 {
 47     age=a;
 48     strcpy(name,n);
 49 }
 50 
 51 //拷贝构造函数
 52 myteacher::myteacher(const myteacher& T)
 53 {
 54     age=T.age;
 55     strcpy(name,T.name);
 56 }
 57 
 58 //打印函数
 59 void myteacher::printT()
 60 {
 61     std::cout<<age<<std::endl;
 62     std::cout<<name<<std::endl;
 63 }
 64 
 65 
 66 //析构函数
 67 myteacher::~myteacher(void)
 68 {
 69 }
 70 
 71 //友元函数
 72 void modifyT(myteacher& pT,int Age,const char* pN)
 73 {
 74     pT.age  = Age;
 75     strcpy(pT.name ,pN);
 76 }
 77 
 78 
 79 mystudent::mystudent(int s=100)
 80 {
 81     score=s;
 82 }
 83 
 84 void mystudent::printT(myteacher& t)
 85 {
 86     std::cout<<"age:"<<t.age<<std::endl;
 87     std::cout<<"name:"<<t.name<<std::endl;
 88 }
 89 
 90 
 91 //main函数
 92 #include<iostream>
 93 #include "myteacher.h"
 94 
 95 using namespace std;
 96 
 97 
 98 int main()
 99 {
100     myteacher t(25,"Wu");
101     t.printT();
102 
103     modifyT(t,26,"Chen");
104     t.printT();
105 
106     mystudent s(98);
107     s.printT(t);
108 
109     system("pause");
110     return 0;
111 }
原文地址:https://www.cnblogs.com/jswu-ustc/p/8343707.html