C++---Friend function and friend class

Friend function :

For the efficiency of the program, it is necessary to allow a function to access the private part of the class; the
friend function itself does not belong to any class; the
friend function is an exception to the package;
the definition and use of the friend function :
1. In order to be in the definition of the class To declare a friend, you need to add the friend keyword;
eg:

class CComplex//复数类
{
    
    
private:
    float r,i;
public:
    CComplex(float x=0,float y=0);
    ~CComplex();
    friend void PrintComplex(CComplex c);
};

void PrintComplex(CComplex c)//实现在类的外部
{
    
    
    cout<<c.r<<"+"<<c.i<<"i"<<endl;
}

2. A friend function can become a friend function of multiple classes. After becoming a friend function of a certain class, you can access all member functions of the class;
3. The calling method of the friend function is the same as that of the general function. ; 4.
C++ does not allow destructors, constructors, and virtual functions to become friend functions;

Tomomoto Metaclass:

If class A is declared as a friend class of another class B, then the members of B can be used by A; the
friend class definition:

friend class 类名;

Friend class instance:

#include <iostream>
#include<string.h>
using namespace std;

class CData
{
    
    
public:
    CData(char *str,int i);
private:
    friend class CShow;//说明友元类CShow;
    char *name;
    int age;
};
CData::CData(char *str,int i):age(i)//注意初始化age的方式!!!
{
    
    
    name=new char(strlen(str)+1);
    strcpy(name,str);
}

class CShow//友元类CShow用来show
{
    
    
public:
    void show(CData x);
};
void CShow::show(CData x)//输出信息
{
    
    
    cout<<"name:"<<x.name<<endl;
    cout<<"age:"<<x.age<<endl;
}

int main()
{
    
    
    CData ob1("liding",21);
    CShow show1;
    show1.show(ob1);
    return 0;
}

Note: The friendship relationship is not reciprocal, nor is it transitive!

Guess you like

Origin blog.csdn.net/timelessx_x/article/details/114591618