[C++] From Beginner to Mastery Part 3 - Friend Functions and Static Class Members

Write the directory title here

static class members

Class members generally need to be accessed through objects and cannot be directly accessed through class names. However, when we define class members as static class members, direct access using class names is allowed.
Static class members define the static keyword before the class member.

  1 #include<iostream>
  2 using namespace std;
  3 class Cbook
  4 {
    
    
  5     public:
  6        static int price;
  7 };
  8 int Cbook::price = 410;
  9 int main()
 10 {
    
    
 11     Cbook cbook;
 12     cout<<"Cbook in"<<Cbook::price<<endl; //通过类名直接访问类成员
 13     cout<<"Cbook use"<<cbook.price<<endl;//通过对象访问静态类成员
 14 
 15 
 16     return 0;
 17 }

Note: When defining static class members, it is usually necessary to initialize the static class members outside the class body.
Static class members are shared by all classes, no matter how many class objects are defined. There is only one copy of the static class members of a class. At the same time, if one object modifies the static class members, then the static class members of other objects will also change (the same static class member is modified)

Static class members can be the type of the current class, and other data class members can only be pointers or application types of the current class. When defining class members, for static class members, their type can be the type of the current class, not the static class· Members are not allowed unless the type of the data member is a pointer or reference type of the current class.

  8 class CBOOK
  9 {
    
    
 10     public:
 11         static int price;
 12     //    CBOOK cbook;错误,非法定义
 13         static CBOOK cook;
 14         CBOOK *cbook;
 15 };

Static class members can be used as default parameters of member functions. When defining member functions of a class, you can specify default parameters for the member function. The default values ​​of its parameters can also be static class members of the class, but different data members cannot be used as member functions. the default parameters.

The static member functions of the class can only access static members of the class, but not ordinary data members.
Moreover, static class member functions cannot be defined as const member functions. If the implementation code of the function is located outside the class body, the static keyword cannot be marked in the implementation part of the function.

Tomomoto

Friend Overview
Friends use the friend keyword to allow a specific function or all member functions of other classes to read and write private data members.
The advantage is that it can keep the data private and allow specific classes or functions to directly access private members.
In order to improve efficiency, friends can allow ordinary functions to directly access the protected or private data members of a class. However, if there is no friend mechanism, the data members of the class can only be declared as public. Thus any function can access it without constraints.
Friend function:

1 #include<iostream>
  2 using namespace std;
  3 class Friendfunction
  4 {
    
       
  5     public:
  6         Friendfunction()
  7         {
    
    
  8             m_height = 0;
  9             m_width = 0;
 10         }
 11         Friendfunction(int height,int width)
 12         {
    
    
 13          m_width = width;
 14          m_height = height;
 15         }
 16         int getHeight()
 17         {
    
    
 18             return m_height;
 19         }
 20         int getWidth()
 21         {
    
    
 22             return m_width;
 23         }
 24         friend int friendfunction(Friendfunction &myret);
 25         protected:
 26         int m_height;
 27         int m_width;
 28 };
 29 int friendfunction(Friendfunction &myret)
 30 {
    
    
 31     return myret.m_height*myret.m_width;
 32 }
 33 int main()
 34 {
    
    
 35     Friendfunction ff(120,210);
 36     cout<<"result = "<<friendfunction(ff)<<endl;
 37 
 38     return 0;
 39 }

In the function friendfunction, you can directly use the data members in the Friendfunction class object because of the effect of the 24th line of code:

 24         friend int friendfunction(Friendfunction &myret);

This example not only protects the hidden data very well, but also allows specific functions from the outside to directly access these hidden data.

Next introduces the friend class:
As shown in line 14 of the code below: friend class Clist; You can declare friend classes. The usage and function are similar to the usage and function of friend function. I won’t go into details here, just look at the code:

  1 #include<iostream>
  2 #include<string>
  3 using namespace std;
  4 class Cltem
  5 {
    
    
  6     private:
  7         string m_name;
  8         void outputname()
  9         {
    
    
 10             cout<<"name = "<<m_name<<endl;
 11             
 12         }
 13     public:
 14        friend class Clist;
 15         void setltemname(string name)
 16         {
    
    
 17            m_name= name;
 18         }  
 19 };      
 20 class Clist
 21 {
    
    
 22     private:
 23         Cltem m_ltem;
 24     public:
 25         void outoutltem();
 26 };
 27 void Clist::outoutltem()
 28 {
    
    
 29     m_ltem.setltemname("beijing");
 30     m_ltem.outputname();
 31 }
 32 int main()
 33 {
    
    
 34     Clist list;
 35     list.outoutltem();
 36 
 37     return 0;
 38 }

When defining the Cltem class, the friend keyword is used to define the Clist class as a friend of the Cltem class. In this way, all methods in the Clist class can access the private members in the Cltem class.

friend method

When we actually develop a program, sometimes we need to control how a class releases private members of the current class. For example, we need to allow only a certain member of the Cbook class to access the private members of the Clibrary class, but not allow other member functions to access the private data of the Clibrary class. This can be achieved by defining a friend function. When defining the Clibrary class, you can define a method of the Cbook class as a friend method, which restricts only that method to access the private members of the Clibrary class.

1 #include<iostream>
  2 using namespace std;
  3 class Clibrary;
  4 class Cbook
  5 {
    
    
  6     public:
  7         Cbook();
  8         ~Cbook();
  9         Clibrary *position;
 10         void putcbook(); //声明友元
 11         //void notfriendcbook();//不声明友元,作为对比
 12 };
 13 class Clibrary
 14 {
    
    
 15     friend void Cbook::putcbook();
 16     private:
 17     string name;
 18     void putname()
 19     {
    
    
 20         cout<<"name = "<<name<<endl;
 21     }
 22     public:
 23     void setname(string name);
 24 };
 25 void Clibrary::setname(string name)
26 {
    
       
 27     this->name = name;
 28 }
 29 void Cbook::putcbook()
 30 {
    
       
 31     position->setname("beijing");
 32     position->putname();
 33 }  /*
 34 void Cbook::notfriendcbook()
 35 {
 36     position->setname("beijing");
 37     position->putname();
 38 }*/
 39 Cbook::Cbook()
 40 {
    
    
 41     position = new Clibrary();
 42 }
 43 Cbook::~Cbook()
 44 {
    
    
 45     delete position;
 46    position = NULL;
 47 }
 48 
 49 int main()
 50 {
    
    
 51     Cbook cook;
 52     cook.putcbook();
 53 
 54    // cook.notfriendcbook();
 55     return 0;
 56 }


As shown in the above code, if a member function without declared friends is released, the following error will occur.

[bsk@localhost c++]$ g++ friendmethod.cpp 
friendmethod.cpp: In member function ‘void Cbook::notfriendcbook()’:
friendmethod.cpp:18:10: error: ‘void Clibrary::putname()’ is private
     void putname()
          ^
friendmethod.cpp:37:23: error: within this context
     position->putname();

The reason is also very simple, because the notfriendcbook() member function is not a friend of the Clibrary class, so this member function cannot access the private properties in the Clibrary class.
In addition, global functions can also be used as class friends and can also access private members in the class.

Finally, let’s talk briefly
When friend functions access members in class objects, they do not need to pass the object name. Friend functions do not have this pointers. If you cannot find non-static members in the class object without using the object name, you cannot access them. But when accessing static members in a class object, you can access them without using the object name.

Guess you like

Origin blog.csdn.net/2202_75623950/article/details/134275286