Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

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

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report