C + + Express (3) __c++

Source: Internet
Author: User
Tags function definition

Reproduced from:
Http://www.cnblogs.com/kkdd-2013/p/5370094.html

C Template 35h 1 friend function and friend Class 2 friend function friend global function friend member function 3 friend function code Practice 4 friend Class 5 friend class code practice 6 Static 7 static code practice 8 operator overloading unary operator overloaded minus sign-member function overloaded minus sign-friend function overload operation Pre-overloaded unary operator overload code practice two-dollar operator overload plus member function overload plus friend function overload output symbol friend function overload index symbol member function overload two-dollar operator overload code Practice 9 function Template 10 variable as template parameter 11 multi-parameter function template 12 function Code practice for templates and overloaded 13 function Templates 14 class template 15 class template code Practice 16 Standard template class vector vector iterator iterator chain list mapping map standard Template Library code practice

7. C + + template 3.5h 7.1 friend function and friend class

Templates in C + + are embodied in functions called template functions, which are called template classes on the class. As a result of extensive use of templates, through the predecessors of the continuous induction and summary, and eventually developed into a set of use norms, powerful, excellent performance standard template class.

In the previous lesson, we mentioned that there is a kind of friend relationship in C + +, and if this kind of relationship is embodied in a function, then we call it a friend function, and if it is embodied in a class, we call it the friend class.

7.2 friend function

For the case where we define the function, one scenario is to define the function as a global function, and the other is to define the function in a class so that it becomes a member function of the class. If the global function is declared as a friend, it becomes a friend global function, and if the member function of a class is declared as a friend function of another class, the member function is called a friend member function. Friend global function

Let's look at an example first.

We define a coordinate class (coordinate), so what if we want to define a friend? We're going to use the keyword: friend. To define a friend function, you only need to add the keyword friend to the function declaration, and then add a semicolon, and be sure to pass in an object of the current class or a reference or a pointer, anyway, This function enables access to the private members of this object or to protected members (as above:friend void printxy (coordinate &c); )。 Let's take a look at what his private members are for coordinate this class. One is that the M_ix represents the horizontal axis, and the one that M_iy represents is the ordinate. Let's take a look at the usage we mentioned.

In the first box, we write the first part of the program called the PRINTXY function, which is the print horizontal ordinate. When you print the horizontal ordinate, we need to pass in a coordinate object or a reference (here is a reference), we need to point out that the incoming reference or pointer, it is more efficient, faster execution, so in this promotion of the incoming reference or pointer, and do not advocate the way to directly into the object. Printxy function When we visit, we just use cout to print the horizontal and vertical coordinates. Please note that the access method we use uses this object to directly access its private members. If we do not declare printxy as a friend of the coordinate, then if we write this, the compiler will certainly report an error. But in the present case, we have declared printxy this function as a friend of the class of coordinate, so we can compile it smoothly through this direct access form. When we call the Printxy function in the Mian function, we need to instantiate a coordinate object and then pass the object in, please note that because the parameter we need is a reference, we can pass it directly to the object name. Instead of adding an address sign (&) to the object name. On the definition of global friend function and the use of a way to say so much, followed by code practice to further deepen the image. Friend member function

Let's use an example to illustrate the problem.

In this case we still take the class of coordinate as an example. The keyword friend is still used when defining. Please note that the function we use is still called printxy, but at this point the PRINTXY function is not a global function, but a member function, which is a member function in the Circle class. So, we're going to declare the member function printxy in circle as a friend of coordinate's class, then we need to write out the Circle class and add it (::) and then Printxy, This allows you to declare a member function of a class as a friend of another class.

In the main function, we instantiate the object coor of a coordinate class, and then instantiate the object circle of a circle class. The implementation of the Printxy in the Circle class is the same as the implementation of the global function described earlier in this paper. With such a call, we can see that if we declare Circle's printxy as a friend of coordinate, then we can directly access the M_ix and M_iy below the object of C when we implement PRINTXY, while M_ix and m_ Iy are the private members of the coordinate, so this behavior can reflect the convenience of friends. Of course, friends bring us convenience at the same time, also brought us a certain degree of risk. When we declare the function of Printxy in circle as a friend function of coordinate this class, it destroys the encapsulation of the coordinate class, while direct access to the data is convenient, But if we accidentally change the value of this data is not easy to erase, so the risk and convenience is often a pair of conflicting. Unless we have special needs, we generally do not recommend excessive use of friends. 7.3 Friend function Code practice

Topic Description:

/* ****************************************** */

/* Friend function

1. Friend Global function

2. Friend member function

/* ****************************************** */

Program Framework:

Let's look at the first part: the Friend global function, the class used is the time class

header file (*time.h*)

#ifndef time_h
#define TIME_H

#include <iostream>
using namespace std;

Class time
{public
: Time
    (int hour, int min, int sec);
Private:
    int m_ihour;
    int m_iminute;
    int m_isecond;
};

#endif

In the time class, we declare the constructor of it and pass in three parameters: when, minutes, seconds, and three private data members, respectively, minutes, seconds. Let's take a look at how its constructors are implemented.

source program (*time.cpp*)

#include "Time.h"

time::time (int hour, int min, int sec)
{
    m_ihour = hour;
    M_iminute = min;
    M_isecond = sec;
}

We see that the implementation of its constructor is very simple, that is, the incoming three parameters are assigned to its three data members respectively.

So, next we define a global function printtime () in the keynote, and in the Printtime () function There is a parameter time (here in the form of a reference), as follows:

void Printtime (Time &t)  //pringttime function definition
{
    cout <<t.m_ihour << ":" <<t.m_iminute << ":" <<t.m_isecond << Endl;
}

When we finish writing, we find that if we do not declare friends, it is equivalent to access its private data members directly through an object, so it is not possible to succeed, so let's click F7 to see if the compilation passes.

We see that the compile process fails, and the failure prompts the private data member in the time class. If we want to access, and we have to declare the Printtime function as a friend function of the time class, how to declare it ... Just add one line of code to the Time.h file: friend void Printtime (Time &c), as shown here:

#ifndef time_h
#define TIME_H

#include <iostream>
using namespace std;
    hour, int min, int sec);
Private:
    int m_ihour;
    int m_iminute;
    int m_isecond;
};

#endif

After that, let's click F7 to see if the compilation will pass ...

We see that when we declare the Printtime function as a friend of the time class, the compilation can pass smoothly.

Next we go to the main function and use it to taste the results we have made.

First, we need to define the object T of a time class, and we need to pass the object T to three parameters: hour, minute, and second. Then, pass t as a parameter into the Printtime function, and see if T can print out the time, minute, and second we passed in ...

main** Function * *

int main ()
{time
    T (6,34,25);
    Printtime (t);
    System ("pause");
    return 0;
}

Let's click F5 to see the results of the operation:

By running the results, we can see that print out the time we passed in in seconds (6:34:25). By declaring a friend, you can make the incoming object accessible to its private data members and member functions (this shows only the way to access its private data members).

Here's another example: a friend member function. The friend member function requires at least two classes to be implemented, so there is another class match (game) defined here. In the class of match, we declare a printtime function, where the Printtime function is the same as the previously defined name, but is now defined within the class and becomes a member function, so in order not to interfere with each other, Let's comment out the previous printtime function.

header file (*match.h*)

#ifndef match_h
#define MATCH_H

class time;//Because the time class is used in the Printtime function, you need to declare the
class MATCH
{

Public:
    void Printtime (Time &t);
}

#endif

Let's change the Time.h file as follows:

#include <iostream>
#include "Match.h"
using namespace std;
Time
    (int hour, int min, int sec);
Private:
    int m_ihour;
    int m_iminute;
    int m_isecond;
};

When we finish this, we can pass an object in Match's printtime and call the private data member in time by using this object: hours, minutes, seconds, as follows:

source program (*match.cpp*)

#include "Match.h"
#include "Time.h"
#include <iostream>
using namespace std;

void Match::p rinttime (Time &t)
{
    cout <<t.m_ihour << ": <<t.m_iminute <<": "< <t.m_isecond << Endl;
}

Then we tune into Demo.cpp, first we need to define a match object m and then call the Printtime function via object m, as follows:

#include <iostream>
#include "stdlib.h"
#include "Time.h"
#include "Match.h"

using namespace STD;

int main ()
{time
    T (6,34,25);
    Match m;
    M.printtime (t);
    System ("pause");
    return 0;
}

Then, we click F7 to see if we can compile it, as follows:

We see that the compiler goes through, and then we press F5 and look at the results of the operation:

We can see that print out is 6 points 34 minutes 25 seconds (6:34:25), the result is as we expected. In addition, as a friend declaration such as Printtime, it does not intersect with the Access qualifier public, private, and protected, that is, they do not form a constraint, so the friend function declaration can be written out of the access qualifier, It can also be written in the access qualifier. This is also verified by an attempt. Visible, the location of the declaration as a friend function is not constrained, but we still suggest that you write it at the very front of the class, that is, to access the qualifier outside, because, as a class, it is very important to expose it externally, and we put the important in front to help reduce the probability of error in the programming process. 7.4 Friend class

The definition of a friend class is very similar to the definition of a friend function, and it also uses the keyword friend, followed by the class name of a class. What you need to pay special attention to is that if we want to declare a friend class, we need to declare the class before the current class, as follows:

Above we declare the Circle class as the friend class of the coordinate class, and declare the circle class before the coordinate class.

Once we have circle this class as a friend of the coordinate class, we can define a coordinate object in the Circle class. And you can access the private data members and member functions of this class coordinate by using this object (in the example above, we define only the data members, not the member functions).

Let's take a look at how you actually define the Circle class.

We see that when we actually define circle, we define a coordinate object M_coor under the Access qualifier private, and in any Circle member function, Can be accessed through this object to access private data members or member functions in the coordinate.

notes about friends The friend relationship cannot be passed (for example: B is a friend, C is a friend of B, but C is not necessarily a friend of a friends of the one-way relationship (for example: A is a friend of B, B is not necessarily a friend, so in the declaration of affinity, Be sure to figure out whether a is a friend of B, or B is a friend of a. The form and number of friend declarations are unrestricted (you can have both friend and friend classes, and the number of declarations is unrestricted)

Note:

Friends are just a complement of encapsulation, which is not a good syntax. In other words, is the last resort to use the grammar, if in the early design ingenious, in fact, can avoid friends. That is, the use of friends destroys encapsulation, making the encapsulation of the class look worse, and thus reflects a sense of directional exposure (who I treat as a friend is the same as the way I expose the data). 7.5 Friend Class Code practice

Topic Description:

/* ****************************************** */

/* Friend class

/* ****************************************** */

Program Framework:

From the program framework, it is the same as the friend function mentioned before, and also defines two classes: One is the time class, the other is the match class. But the content here is different from the previous one, let's have a look.

First of all, in the time class (Time.h file), we define a member function Printtime () under private, where the member function is three data members: hour, minute, and second.

header file (*time.h*)

#ifndef time_h
#define TIME_H

class time
{public    
: Time
    (int hour, int min, int sec);
Private:
    void Printtime (); 
    int m_ihour;
    int m_iminute;
    int m_isecond;
};

#endif

Let's take a look at how the Printtime function is defined and jump into the Time.cpp

source program (*time.cpp*)

#include "Time.h"
#include <iostream>
using namespace std;

Time::time (Inthour, Intmin, intsec)
{
    m_ihour = hour;
    M_iminute = min;
    M_isecond = sec;
}
void time::p rinttime ()
{
    cout << m_ihour << "when" << m_iminute << "Minutes" << M_isecond << "SEC" << Endl;
}

In addition, we have added a member function testtime () in the MATCH.H, and implemented in Match.cpp, which is called by the data member M_ttimer to be timely and divided. Seconds data member. We can see that both the member function and the data member are written under private in the time class. Let's take a look at the data member in MATCH.H, which is a time data member M_ttimer (timing). as follows:

header file (*match.h*)

#ifndef match_h
#define MATCH_H

#include "Time.h"

class MATCH
{public
:
    match (int hour, int Min, int sec);
    void Testtime ();
Private: Time
    M_ttimer;

#endif

source program (*match.cpp*)

#include "Match.h"
#include <iostream>
using namespace std;

Match::match (int hour, int min, int sec): M_ttimer (Hour, Min, sec)//To instantiate the M_ttimer's three parameters by initializing the list
{
   //to do
}

void Match::testtime ()
{
    m_ttimer.printtime ();
    cout << m_ttimer.m_ihour << ":" << m_ttimer.m_iminute << ":" << m_ttimer.m_isecond << Endl;
}

Keynote Program (*demo.cpp*)

#include <iostream>
#include "stdlib.h"
#include "Time.h"
#include "Match.h"

using namespace Std;

int main ()
{
    Match m (6,30,56);
    M.testtime ();

    System ("pause");
    return 0;
}

Here we instantiate a match object M and pass in three parameters: time and minutes, then call the Testtime () function through the object m.

Program to this we did not declare match as its friend class in Time.h, so when we press F7, we can see:

That is, the Printtime function or data member that we call at this time is not invoked because it is a private access form.

So at this point, we need to go to the Time.h file and declare the match class as a friend class of the time class, as follows:

#ifndef time_h
#define TIME_H

class match;//because to declare a friend, you must first declare
class time
{
    friend Match;// Declare the friend class of the match class as the time class public
: Time
    (int hour, int min, int sec);
Private:
    void Printtime (); 
    int m_ihour;
    int m_iminute;
    int m_isecond;
};

#endif

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.