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

Listing 15.15 shows the implementation of the methods that weren’t already defined inline in Listing 15.14. Note that nested classes require using the scope-resolution operator more than once. Also note that the operator[]() functions throw exceptions if the array index is out of bounds.

Listing 15.15. sales.cpp

// sales.cpp -- Sales implementation

#include "sales.h"

using std::string;

Sales::bad_index::bad_index(int ix, const string & s )

    : std::logic_error(s), bi(ix)

{

}

Sales::Sales(int yy)

{

    year = yy;

    for (int i = 0; i < MONTHS; ++i)

        gross[i] = 0;

}

Sales::Sales(int yy, const double * gr, int n)

{

    year = yy;

    int lim = (n < MONTHS)? n : MONTHS;

    int i;

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

        gross[i] = gr[i];

    // for i > n and i < MONTHS

    for ( ; i < MONTHS; ++i)

        gross[i] = 0;

}

double Sales::operator[](int i) const

{

    if(i < 0 || i >= MONTHS)

        throw bad_index(i);

    return gross[i];

}

double & Sales::operator[](int i)

{

    if(i < 0 || i >= MONTHS)

        throw bad_index(i);

    return gross[i];

}

LabeledSales::nbad_index::nbad_index(const string & lb, int ix,

           const string & s ) : Sales::bad_index(ix, s)

{

    lbl = lb;

}

LabeledSales::LabeledSales(const string & lb, int yy)

         : Sales(yy)

{

    label = lb;

}

LabeledSales::LabeledSales(const string & lb, int yy,

                           const double * gr, int n)

                                  : Sales(yy, gr, n)

{

    label = lb;

}

double LabeledSales::operator[](int i) const

{    if(i < 0 || i >= MONTHS)

        throw nbad_index(Label(), i);

    return Sales::operator[](i);

}

double & LabeledSales::operator[](int i)

{

    if(i < 0 || i >= MONTHS)

        throw nbad_index(Label(), i);

    return Sales::operator[](i);

}

Listing 15.16 uses the classes in a program that first tries to go beyond the end of the array in the LabeledSales object sales2 and then beyond the end of the array in the Sales object sales1. These attempts are made in two separate try blocks that test for each kind of exception.

Listing 15.16. use_sales.cpp

// use_sales.cpp  -- nested exceptions

#include

#include "sales.h"

int main()

{

    using std::cout;

    using std::cin;

    using std::endl;

    double vals1[12] =

    {

        1220, 1100, 1122, 2212, 1232, 2334,

        2884, 2393, 3302, 2922, 3002, 3544

    };

    double vals2[12] =

    {

        12, 11, 22, 21, 32, 34,

        28, 29, 33, 29, 32, 35

    };

    Sales sales1(2011, vals1, 12);

    LabeledSales sales2("Blogstar",2012, vals2, 12 );

    cout << "First try block:\n";

    try

    {

        int i;

        cout << "Year = " << sales1.Year() << endl;

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

        {

            cout << sales1[i] << ' ';

            if (i % 6 == 5)

                cout << endl;

        }

        cout << "Year = " << sales2.Year() << endl;

        cout << "Label = " << sales2.Label() << endl;

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

        {

            cout << sales2[i] << ' ';

            if (i % 6 == 5)

                cout << endl;

        }

        cout << "End of try block 1.\n";

   }

   catch(LabeledSales::nbad_index & bad)

   {

        cout << bad.what();

        cout << "Company: " << bad.label_val() << endl;

        cout << "bad index: " << bad.bi_val() << endl;

   }

   catch(Sales::bad_index & bad)

   {

        cout << bad.what();

        cout << "bad index: " << bad.bi_val() << endl;

   }

   cout << "\nNext try block:\n";

   try

    {

        sales2[2] = 37.5;

        sales1[20] = 23345;

        cout << "End of try block 2.\n";

   }

   catch(LabeledSales::nbad_index & bad)

   {

        cout << bad.what();

        cout << "Company: " << bad.label_val() << endl;

        cout << "bad index: " << bad.bi_val() << endl;

   }

   catch(Sales::bad_index & bad)

   {

        cout << bad.what();

        cout << "bad index: " << bad.bi_val() << endl;

   }

   cout << "done\n";

    return 0;

}

Here is the output of the program in Listings 15.14, 15.15, and 15.16:

First try block:

Year = 2011

1220 1100 1122 2212 1232 2334

2884 2393 3302 2922 3002 3544

Year = 2012

Label = Blogstar

12 11 22 21 32 34

28 29 33 29 32 35

Index error in LabeledSales object

Company: Blogstar

bad index: 12

Next try block:

Index error in Sales object

bad index: 20

done

When Exceptions Go Astray

After an exception is thrown, it has two opportunities to cause problems. First, if it is thrown in a function that has an exception specification, it has to match one of the types in the specification list. (Remember that in an inheritance hierarchy, a class type matches objects of that type and of types descended from it.) If the exception doesn’t match the specification, the unmatched exception is branded an unexpected exception, and, by default, it causes the program to abort. (Although C++11 deprecates exception specifications, they still remain in the language and in some existing code.) If the exception passes this first hurdle (or avoids it because the function lacks an exception specification), it then has to be caught. If it isn’t, which can happen if there is no containing try block or no matching catch block, the exception is branded an uncaught exception, and by default, it causes the program to abort. However, you can alter a program’s response to unexpected and uncaught exceptions. Let’s see how, beginning with uncaught exceptions.

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

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

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

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