Get the App
SLTechnology News&Howtos  ›  Development  › 

Example Analysis of friend function and friend Class in C++

Shulou Source: shulou.com Published: 2022-06-01 12:24:40 09月12日 Update

Xiaobian to share with you C++ friend function and friend class example analysis, I believe most people do not know how to share this article for your reference, I hope you read this article after a great harvest, let us go to understand it!

I. Background of the problem

Encapsulation of classes is one of the three major features of C++. Encapsulated data is inaccessible outside the class. But once something goes wrong, what if you want to manipulate encapsulated data? Thus the friend class of the friend function is born. A function or class declared with the friend keyword in a class can operate on any permission member property in the class body

There are advantages and disadvantages friend function, friend class serious damage to the encapsulation of the class, less than forced not to use.

Second, friend function

declaration part: friend returns the type function name (parameter list);

Definition section: return type function name (parameter list){

The body of a function, in which operators can operate on the member variables of the corresponding object

};

A friend function is a global function that becomes a friend of some class and can modify its private properties at will.

The specific usage method is as follows:

#includeusing namespace std;class test_Y {private: int a; int b;public: test_Y(int a=0,int b=0) { this->a = a; this->b = b; } int getA() { return a; } int getB() { return b; } void print() { cout b = b; } void print() { cout a; a.b = this->b; } void print() { cout

Tags: Functions members objects variables attributes wrappers parts clocking methods articles examples friends analysis necessity usage content parameters data time properties Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Linux Shulou Technology Shulou Information Shulou Tech Info