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

// sayings2.cpp -- using pointers to objects

// compile with string1.cpp

#include

#include       // (or stdlib.h) for rand(), srand()

#include         // (or time.h) for time()

#include "string1.h"

const int ArSize = 10;

const int MaxLen = 81;

int main()

{

    using namespace std;

    String name;

    cout <<"Hi, what's your name?\n>> ";

    cin >> name;

    cout << name << ", please enter up to " << ArSize

         << " short sayings :\n";

    String sayings[ArSize];

    char temp[MaxLen];               // temporary string storage

    int i;

    for (i = 0; i < ArSize; i++)

    {

        cout << i+1 << ": ";

        cin.get(temp, MaxLen);

        while (cin && cin.get() != '\n')

            continue;

        if (!cin || temp[0] == '\0') // empty line?

            break;                   // i not incremented

        else

            sayings[i] = temp;       // overloaded assignment

    }

    int total = i;                   // total # of lines read

    if (total > 0)

    {

        cout << "Here are your sayings:\n";

        for (i = 0; i < total; i++)

            cout << sayings[i] << "\n";

    // use pointers to keep track of shortest, first strings

        String * shortest = &sayings[0]; // initialize to first object

        String * first = &sayings[0];

        for (i = 1; i < total; i++)

        {

            if (sayings[i].length() < shortest->length())

                shortest = &sayings[i];

            if (sayings[i] < *first)     // compare values

                first = &sayings[i];     // assign address

        }

        cout << "Shortest saying:\n" << * shortest << endl;

        cout << "First alphabetically:\n" << * first << endl;

        srand(time(0));

        int choice = rand() % total; // pick index at random

    // use new to create, initialize new String object

        String * favorite = new String(sayings[choice]);

        cout << "My favorite saying:\n" << *favorite << endl;

        delete favorite;

    }

    else

        cout << "Not much to say, eh?\n";

    cout << "Bye.\n";

    return 0;

}

Object Initialization with new

In general, if Class_name is a class and if value is of type Type_name, the statement

Class_name * pclass = new Class_name(value);

invokes this constructor:

Class_name(Type_name);

There may be trivial conversions, such as to this:

Class_name(const Type_name &);

Also the usual conversions invoked by prototype matching, such as from int to double, takes place as long as there is no ambiguity. An initialization in the following form invokes the default constructor:

Class_name * ptr = new Class_name;

Here’s a sample run of the program in Listing 12.7:

Hi, what's your name?

>> Kirt Rood

Kirt Rood, please enter up to 10 short sayings :

1: a friend in need is a friend indeed

2: neither a borrower nor a lender be

3: a stitch in time saves nine

4: a niche in time saves stine

5: it takes a crook to catch a crook

6: cold hands, warm heart

7:

Here are your sayings:

a friend in need is a friend indeed

neither a borrower nor a lender be

a stitch in time saves nine

a niche in time saves stine

it takes a crook to catch a crook

cold hands, warm heart

Shortest saying:

cold hands, warm heart

First alphabetically:

a friend in need is a friend indeed

My favorite saying:

a stitch in time saves nine

Bye

Because the program selects the favorite saying randomly, different runs of the program will show different choices, even for identical input.

Looking Again at new and delete

Note that the program generated from Listings 12.4, 12.5, and 12.7 uses new and delete on two levels. First, it uses new to allocate storage space for the name strings for each object that is created. This happens in the constructor functions, so the destructor function uses delete to free that memory. Because each string is an array of characters, the destructor uses delete with brackets. Thus, memory used to store the string contents is freed automatically when an object is destroyed. Second, the code in Listing 12.7 uses new to allocate an entire object:

String * favorite = new String(sayings[choice]);

This allocates space not for the string to be stored but for the object—that is, for the str pointer that holds the address of the string and for the len member. (It does not allocate space for the num_strings member because it is a static member that is stored separately from the objects.) Creating the object, in turn, calls the constructor, which allocates space for storing the string and assigns the string’s address to str. The program then uses delete to delete this object when it is finished with it. The object is a single object, so the program uses delete without brackets. Again, this frees only the space used to hold the str pointer and the len member. It doesn’t free the memory used to hold the string str points to, but the destructor takes care of that final task (see Figure 12.4).

Figure 12.4. Calling destructors.

Again, destructors are called in the following situations (refer to Figure 12.4):

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

Все книги серии 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.

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

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