C + + template implementations of queues (friend functions and operator overloading)

Source: Internet
Author: User

One: Cause

(0) Take out the queue that I realized at the beginning of the year, the first time with C + + class to implement the queue, in and now realize the other complex STL contrast, the mood is extremely complex;

Note: It is a kind of enjoyment to hear what you have written, and to listen to your childish is also a kind of beauty.

(1) Less gossip, I am now answering my own question in three (5), the return value of the function is bool or void type?? in fact, the return value of the function is bool or void depending on the case: for example, the NULL function bool IsEmpty (), the comparison operator overload function bool operator >= (&) and other judgment functions; And like Swap Swap (&,&), clear Clear (), insert (), delete (), Push,pop, and so on general void is possible.

(2) Is it the return value of the return value of the function, or the return value by the application of the parameter? is still depending on the situation, if the return of multi-value, can only pass the parameters; The following is a case of returning a single value, most of which is returned by a function return value only like swap (&,&) (the class member function is a parameter of the Oh, the default has an implied this pointer), reverse () and so on.

< Span style= "font-size:14.4444446563721px" > (3) The problem now is   is a member variable of a class (private or common), or global, that can return a reference. But the return reference is risky, such as, T&  front () { return  head->data;} In the main function, the data values can be modified by linkage.

(4) Again const as function friend  MyString  operator+ ( const  MyString & T1, const  mystring& T2); Description T1 T2 is an immutable application parameter, which is simply a reference to reduce overhead, is not used as a function return value, the return value type is a mystring type (non-reference), which means that the function's local parameters are returned.

< Span style= "font-size:14.4444446563721px" > (5) See this function again  const int &operator[] (const size_t) const;
  The first const is the return value, returns a constant reference, cannot be modified, and the second const is a parameter that indicates that the parameter is not modified within the function; the last const is that the this pointer points to a const, which is within this function, All members of this class are equivalent to Const.

The third const also participates in the distinction of overloaded functions, so that a new overloaded form is formed with the same number of parameter types. It is important to note that the constant member function is the only external interface of the constant object, which should be noted. The constant member function cannot update the object's data member, nor can it call the normal member function in the class.

(6) Friend class, not much to say, please see the example bar

Suppose we want to design a program that simulates a TV set and a remote control. Everyone's way, the remote control machine and TV class is not included, and, the remote control can operate the TV, but the TV cannot operate the remote control, which is more in line with the characteristics of friends. That is, we describe the remote control class as a friend of the TV class. Here is the code for this example: #include <iostream>usingnamespacestd;classTV{public:friendclassTele; TV (): On_off (Off), volume (+), channel (3), mode (TV) {}

(7) explained a little, I have been naïve, is still relatively naïve, but I believe that as long as the original dream of the people, will eventually go to maturity;

(8) Once again thank oneself can adhere to the original dream, I believe you also have a similar dream, do not envy others talent, other people's success can not be copied, other people's glory will not repeat, only our own down-to-earth walk every step, sow our own dream seeds, stride forward.

Two: Code presentation

(1) Queue class

 #include <iostream>using namespace Std;template<typename t> class Queue;template<typename T>class    queue_item{Friend class queue<t>;    Queue_item (const t &i): Item (i), next (0) {}//Next default value T item; Queue_item *next;};/ /And struct-like oh, of course, can also be changed to struct oh template<typename t>class queue{public:queue (): Head (0), tail (0), n (0) {}//==0 must have    , do you want the initial value of head tail?    Queue (const queue &q);    Queue &operator= (const queue &q);    ~queue ();    void push (const T &key);    void Pop ();    BOOL Front (T &item);    BOOL Back (T &item);  BOOL Is_empty () {return n = = 0;    } size_t Size () {return n;  } void Clear ();    Private:queue_item<t> *head;    Queue_item<t> *tail;//Queue_item does not have a default constructor and does not know why it can be declared, because he is a pointer, allocating only pointer-sized memory, not allocating size_t N of object memory; void Copy_item (const queue &q);};/ /Team Tail add element template<typename t>void queue<t>::p ush (const T &key) {queue_item<t> *item = new Queue_it Em<t>(key);    if (n = = 0) head = Tail = Item; else {Tail->next = item;//head points to the first element of the team tail = tail->next;//tail points to the node just entered} n++;    Delete the first element of the team Template<typename t>void Queue<t>::p op () {if (n = = 0) return;        else {queue_item<t> *tmp = head;        Head = head->next;        Delete tmp;    n--; } return;    Returns the first element of the team Template<typename T>bool Queue<t>::front (T &item) {if (n = = 0) return false;    ELSE item = head->item; return true;}    Returns the tail element template<typename T>bool queue<t>::back (T &item) {if (n = = 0) return false;    ELSE item = tail->item; return true;}    Template<typename t>void queue<t>::clear () {//if (n = = 0) return false;    while (n > 0) {pop (); }//return true;} Copy constructor Template<typename t>queue<t>::queue (const queue &q): Head (0), tail (0), n (0) {copy_item (q);} destructor Template<typename T>queue<t>::~qUeue () {clear ();} operator overloaded function Template<typename t>queue<t> &queue<t>::operator = (Const queue &q) {if (This! = &amp        ; q) {clear ();        n = 0;    Copy_item (q); } return *this;} Deep copy function Template<typename t>void queue<t>::copy_item (const queue &q) {queue_item<t> *tmp = Q.hea    D        while (tmp! = NULL) {push (Tmp->item);    TMP = tmp->next; }}
(2) Main function test

#include <cstdlib> #include <iostream> #include <string>using namespace std;//test the queue class Templateint Main (int argc, char *argv[]) {queue<int> q;int front,back;if (Q.is_empty ()) cout << "Empty" <&l T Endl;elsecout << "not Empty" << endl;q.push (1); Q.push (2); Q.push (3); Q.push (4);queue<int> Q2 (q);    Q.clear (); if (Q.is_empty ()) cout << "Empty" << endl;elsecout << "not empty" << Endl;    Q2.front (front); Q2.back (back), cout << "Queue 2:" << front << endl;cout << "Queue 2:" << back << Endl    ; cout << "The size of the queue 2:" << q2.size () << endl;q = Q2;q.front (front); Q.back (back), cout << "Queue 1:" << front << endl;cout << "Queue 1:" << back << Endl; Queue<string> Qs;qs.push ("Gauss"); Qs.push ("Randy"); Qs.push ("Jiawenjie"); string S1,s2;qs.front (S1); Qs.back ( S2) cout << s1 << endl;cout << S2 << enDl;return exit_success;} 
Three: Experience and summary

1. If any one of the constructors is defined in a class, and no default constructor is defined, it is not possible to define the object of the class as: Class a{}; a AA; (This is wrong)
But a *pa; (this is legal, because only a pointer is defined, no constructor is called, no memory is allocated for the class object)
2. The private and protected members of a class cannot be accessed outside the class, but this rule does not affect friend (friend) if we want to declare an external function as the class's
Friend (friend), so that this function accesses the private and protected members of this class, we declare it in the class body by the prototype of this external function, plus the keyword friend.
3, the Class A is declared as a friend of Class B (Friends), at this time a class is the Class B friend, all the friends of the Class A is a Class B friend function, you can access all the private members of Class B
variable, but not equal to Class B is a friend of Class A, the member function of Class B cannot access the private member variable of Class A.
4, operator overloading is also generally declared as a friend function (friend),
5, there are still two points are not very clear, please Daniel pointing-the function of the return value is the type bool or void?? Is it the return value of the function return value, or the return value by the application of the parameter?

C + + template implementations of queues (friend functions and operator overloading)

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.