C ++ Programming Learning (nine) this friend function pointer &

 

mooc NPU Wei Ying teacher's curriculum channel is closed, and uncomfortable. Now watching engineering codes to relive the side brush first pass C ++ knowledge point of time, did not follow the order to outline, think of what to write where.

 

It is doing this with?

Description : In C ++, each object can be accessed through  this  to access your address pointer. this  pointer is hidden parameters of all member functions. Therefore, within the member function, which can be used to point (meaning all members can access the current object) call the object.

 

Essence : this parameter is actually a member function, member function is called when the actual address of the object passed as arguments to this. This parameter, however this is implicit, it does not appear in the code, but rather silently at compile time by a compiler, add it to the list of parameters.
this as an implicit parameter, is essentially a function of the local member variable, it can only be used inside the member function, and only to the assignment when this member function calls by the object.
In the "realization of a C ++ function compiler theory and member functions" section mentioned, the member function eventually be compiled into an ordinary function object has nothing to do, in addition to member variables, lose all the information, so the compiler when you want to add a member function in additional parameters, the current first address of the object passed in order to associate member functions and member variables. This additional parameter is actually this, it is a bridge member functions and member variables associated with it.

 

Note : friend function no  this  pointer, because a friend is not a member of the class. Only member functions have  this  pointer.

(The question is , what is a friend? See the end of the text)

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class Student{
 5 public:
 6     void setname(char *name);
 7     void setage(int age);
 8     void setscore(float score);
 9     void show();
10 private:
11     char *name;
12     int age;
13     float score;
14 };
15 
16 void Student::setname(char *name){
17     this->name = name;
18 }
19 void Student::setage(int age){
20     this->age = age;
21 }
22 void Student::setscore(float score){
23     this->score = score;
24 }
25 void Student::show(){
26     cout<<this->name<<"的年龄是"<<this->age<<",成绩是"<<this->score<<endl;
27 }
28 
29 int main(){
30     Student *pstu = new Student;
31     pstu -> setname("李华");
32     pstu -> setage(16);
33     pstu -> setscore(96.5);
34     pstu -> show();
35 
36     return 0;
37 }

Operating results are:

1 Li Hua's age is 16, the score is 96. The 5

this can only be used within the class, all members have access through this class, including private, protected, public property.

Member function in the present embodiment parameters and member variable name is duplicated only through this distinction. As a member function setname(char *name), for example, its parameter is a name, and member variables namethe same name, if writing name = name;this statement, is to give formal parameter nameassignment, but not to the member variable nameassignment. Writing this -> name = name;later, =the left nameis the member variable, the right nameis the formal parameters at a glance.

Note, this is a pointer to use ->to access the member variables or member functions.

Although this use within the class, but only if given this assignment after the object is created, and this assignment process is completed compiler automatically, without user intervention, the user can not explicitly give this assignment. In the present embodiment, the value of this pstu and are the same.

We wish to prove it, to add a Student class member function printThis(), designed to output this value, as follows:

. 1  void Student :: printThis () {
 2      COUT << the this << endl;
 . 3  }
 . 4  // then () function call to create the object in the main and printThis (): 
. 5 Student * = pstu1 new new Student;
 . 6 pstu1 -> printThis ();
 . 7 COUT pstu1 << << endl;
 . 8  
. 9 Student * = pstu2 new new Student;
 10 pstu2 -> printThis ();
 . 11 COUT pstu2 << << endl;

operation result:

1 0x7b17d8
2 0x7b17d8
3 0x7b17f0
4 0x7b17f0

Can be found, this really points to the current object, but also for different objects, this value is not the same.

Few things to note:

  • this is const pointer, its value can not be modified, all attempts to modify the operation of the pointer, such as assignment, increasing, decreasing and the like are not allowed.
  • this function uses only internal members, with no sense elsewhere, it is also illegal.
  • This makes sense only if the object is created, it can not be used in static member function (follow-up will be talked about static members).

 

What is a friend?

For all members of the private part of the program outside the class are hidden from public access they need to call a member function, but sometimes may also need to create an exception to the rule.

Friend function is a function that does not belong to the class members, but it can access private members of the class. In other words, friend function is considered like a member of the class. Friend function may be a conventional stand-alone function, may also be other members of the class. In fact, the whole class can be declared as a friend of another class.

In order for a function or class to be a friend of another class, must be declared by the grant it access to classes. Class retained their friends' list ", only those whose names appear in the list of external function or class was only granted access. By keyword friend placed before the function prototype, a function can be declared as a friend.

In the following statement Budget class, addBudget function Aux another class that was declared as a friend:

 1 class Budget
 2 {
 3     private:
 4         static double corpBudget;
 5         double divBudget;
 6     public:
 7         Budget() { divBudget = 0; }
 8         void addBudget(double b)
 9         {
10             divBudget += b;
11             corpBudget += divBudget;
12         }
13         double getDivBudget() const { return divBudget; }
14         static double getCorpBudget() { return corpBudget; }
15         static void mainOffice(double);
16         friend void Aux::addBudget (double) ; // 友元
17 };

Another subsidiary Aux assume office on behalf of a class division, perhaps in another country. Affiliated office proposed a separate budget requirements which must be added to the budget for the entire enterprise. The Aux :: addBudget friend function declaration tells the compiler that this function has been granted access to private members of the Budget authority. Preclude the use of the function arguments of type double, it represents the amount of business to be added to the budget: 

1 class Aux
2 {
3     private:
4         double auxBudget;
5     public:
6         Aux() { auxBudget =0; }
7         void addBudget(double);
8         double getDivBudget() { return auxBudget; }
9 };

The following are definitions Aux addBudget member functions:

1  void For :: addBudget ( dual b)
 2  {
 3      auxBudget + = b;
4      Budget :: corpBudget + = auxBudget;
5 }

Parameter b is added to the enterprise budget, which is :: corpBudget to access and realized by using the expression Budget. The following program demonstrates the use of these classes in the full program.

  1 //auxil.h的内容
  2 #ifndef AUXIL_H
  3 #define AUXIL_H
  4 // Aux class declaration.
  5 class Aux
  6 {
  7     private:
  8         double auxBudget;
  9     public:
 10         Aux() { auxBudget = 0; }
 11         void addBudget(double);
 12         double getDivBudget() const { return auxBudget; }
 13 };
 14 #endif
 15 //budget3.h的内容
 16 #ifndef BUDGET3_H
 17 #define BUDGET3_H
 18 #include "auxil.h" // For Aux class declaration
 19 //Budget class declaration.
 20 class Budget {
 21     private:
 22         static double corpBudget;
 23         double divBudget;
 24     public:
 25         Budget() { divBudget =0; }
 26         void addBudget(double b)
 27         {
 28             divBudget += b;
 29             corpBudget += divBudget;
 30         }
 31         double getDivBudget() const {return divBudget;}
 32         static double getCorpBudget() {return corpBudget;}
 33         static void mainOffice(double);
 34         friend void Aux::addBudget(double);
 35 };
 36 #endif
 37 
 38 //budget3.cpp的内容
 39 #include "budget3.h"
 40 //Definition of static member.
 41 double Budget::corpBudget = 0;
 42 void Budget:imainOffice(double budReq)
 43 {
 44     corpBudget += budReq;
 45 }
 46 
 47 //auxil.cpp的内容
 48 #include "auxil.h"
 49 #include "budget3.h"
 50 void Aux::addBudget(double b)
 51 {
 52     auxBudget += b;
 53     Budget::corpBudget += auxBudget;
 54 }
 55 
 56 //main程序的内容
 57 //This program demonstrates a static class member variable. #include <iostream>
 58 #include <iomanip>
 59 #include "budget3.h"
 60 using namespace std;
 61 
 62 int main()
 63 {
 64     const int N_DIVISIONS = 4;
 65     // Get the budget requests for the divisions and offices
 66     cout << "Enter the main office's budget request:";
 67     double amount;
 68     cin >> amount;
 69     Budget:imainOffice(amount);
 70     // Create the division and auxiliary offices
 71     Budget divisions [N_DIVISIONS];
 72     Aux auxOffices[N_DIVISIONS];
 73     cout << "\nEnter the budget requests for the divisions and" << "\ntheir auxiliary offices as prompted:\n";
 74     for (int count = 0; count < N_DIVISIONS; count++)
 75     {
 76         double bud;
 77         cout << "Division " << (count + 1) << ": ";
 78         cin >> bud;
 79         divisions[count].addBudget(bud);
 80         cout << "Division " << (count + 1) << "'s auxiliary office:";
 81         cin >> bud;
 82         auxOffices[count].addBudget(bud);
 83     }
 84 
 85     // Print the budgets
 86     cout << setprecision (2);
 87     cout << showpoint << fixed;
 88     cout << "Here are the division budget requests:\n";
 89     for (int count = 0; count < N_DIVISIONS; count++)
 90     {
 91         cout << "\tDivision: " << (count + 1) << "\t\t\t$ ";
 92         cout << setw(7);
 93         cout << divisions[count].getDivBudget() << endl;
 94         cout << "\tAuxiliary Office of Division " << (count+1);
 95         cout << "\t$ ";
 96         cout << auxOffices[count].getDivBudget() << endl;
 97     }
 98 
 99     // Print total requests
100     cout << "\tTotal Requests (including main office): $ ";
101     cout << Budget::getCorpBudget() << endl;
102     return 0;
103 }

Note that, as described above, the entire category to be a friend of another class. Budget class can Aux class to be a friend by the following statement:

friend class Aux;

However, this may not be a good idea because it will lead to each member of Aux function (including functions that may be added later) can access private members of the Budget. Therefore, the best practice is to declare only those functions that must have access to private members of the class as a friend.

  

 

 

 

 

 

 

参考:【1】https://www.runoob.com/cplusplus/cpp-this-pointer.html

【2】http://c.biancheng.net/view/2226.html

【3】http://c.biancheng.net/view/1489.html

Infringement deleted.

Guess you like

Origin www.cnblogs.com/JuiceCat/p/12160668.html