Читаем C++ Primer Plus полностью

These same scope considerations apply to nested structures and enumerations, too. Indeed, many programmers use public enumerations to provide class constants that can be used by client programmers. For example, the many implementations of classes defined to support the iostream facility use this technique to provide various formatting options, as you’ve already seen (and will explore more fully in Chapter 17, “Input, Output, and Files”). Table 15.1 summarizes scope properties for nested classes, structures, and enumerations.

Table 15.1. Scope Properties for Nested Classes, Structures, and Enumerations

Access Control

After a class is in scope, access control comes into play. The same rules govern access to a nested class that govern access to a regular class. Declaring the Node class in the Queue class declaration does not grant the Queue class any special access privileges to the Node class, nor does it grant the Node class any special access privileges to the Queue class. Thus, a Queue class object can access only the public members of a Node object explicitly. For that reason, the Queue example makes all the members of the Node class public. This violates the usual practice of making data members private, but the Node class is an internal implementation feature of the Queue class and is not visible to the outside world. That’s because the Node class is declared in the private section of the Queue class. Thus, although Queue methods can access Node members directly, a client using the Queue class cannot do so.

In short, the location of a class declaration determines the scope or visibility of a class. Given that a particular class is in scope, the usual access control rules (public, protected, private, friend) determine the access a program has to members of the nested class.

Nesting in a Template

You’ve seen that templates are a good choice for implementing container classes such as the Queue class. You may be wondering whether having a nested class poses any problems to converting the Queue class definition to a template. The answer is no. Listing 15.5 shows how this conversion can be made. As is common for class templates, the header file includes the class template, along with method function templates.

Listing 15.5. queuetp.h

// queuetp.h -- queue template with a nested class

#ifndef QUEUETP_H_

#define QUEUETP_H_

template

class QueueTP

{

private:

    enum {Q_SIZE = 10};

    // Node is a nested class definition

    class Node

    {

    public:

        Item item;

        Node * next;

        Node(const Item & i):item(i), next(0){ }

    };

    Node * front;       // pointer to front of Queue

    Node * rear;        // pointer to rear of Queue

    int items;          // current number of items in Queue

    const int qsize;    // maximum number of items in Queue

    QueueTP(const QueueTP & q) : qsize(0) {}

    QueueTP & operator=(const QueueTP & q) { return *this; }

public:

    QueueTP(int qs = Q_SIZE);

    ~QueueTP();

    bool isempty() const

    {

        return items == 0;

    }

    bool isfull() const

    {

        return items == qsize;

    }

    int queuecount() const

    {

        return items;

    }

    bool enqueue(const Item &item); // add item to end

    bool dequeue(Item &item);       // remove item from front

};

// QueueTP methods

template

QueueTP::QueueTP(int qs) : qsize(qs)

{

    front = rear = 0;

    items = 0;

}

template

QueueTP::~QueueTP()

{

    Node * temp;

    while (front != 0)      // while queue is not yet empty

    {

        temp = front;       // save address of front item

        front = front->next;// reset pointer to next item

        delete temp;        // delete former front

    }

}

// Add item to queue

template

bool QueueTP::enqueue(const Item & item)

{

    if (isfull())

        return false;

    Node * add = new Node(item);    // create node

// on failure, new throws std::bad_alloc exception

    items++;

    if (front == 0)         // if queue is empty,

        front = add;        // place item at front

    else

        rear->next = add;   // else place at rear

    rear = add;             // have rear point to new node

    return true;

}

// Place front item into item variable and remove from queue

template

bool QueueTP::dequeue(Item & item)

{

    if (front == 0)

        return false;

    item = front->item;     // set item to first item in queue

    items--;

    Node * temp = front;    // save location of first item

    front = front->next;    // reset front to next item

    delete temp;            // delete former first item

    if (items == 0)

        rear = 0;

    return true;

}

 #endif

One interesting thing about the template in Listing 15.5 is that Node is defined in terms of the generic type Item. Thus, a declaration like the following leads to a Node defined to hold type double values:

QueueTp dq;

And the following declaration leads to a Node defined to hold type char values:

QueueTp cq;

These two Node classes are defined in two separate QueueTP classes, so there is no name conflict between the two. That is, one node is type QueueTP::Node, and the other is type QueueTP::Node.

Перейти на страницу:

Все книги серии Developer's Library

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных

Похожие книги

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

Алексей Анатольевич Гладкий

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

Финансы / Программирование, программы, базы данных