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

        cout << "Negative deposit not allowed; "

             << "deposit is cancelled.\n";

    else

        balance += amt;

}

void Brass::Withdraw(double amt)

{

    // set up ###.## format

    format initialState = setFormat();

    precis prec = cout.precision(2);

    if (amt < 0)

        cout << "Withdrawal amount must be positive; "

             << "withdrawal canceled.\n";

    else if (amt <= balance)

        balance -= amt;

    else

        cout << "Withdrawal amount of $" << amt

             << " exceeds your balance.\n"

             << "Withdrawal canceled.\n";

    restore(initialState, prec);

}

double Brass::Balance() const

{

    return balance;

}

void Brass::ViewAcct() const

{

     // set up ###.## format

    format initialState = setFormat();

    precis prec = cout.precision(2);

    cout << "Client: " << fullName << endl;

    cout << "Account Number: " << acctNum << endl;

    cout << "Balance: $" << balance << endl;

    restore(initialState, prec); // restore original format

}

// BrassPlus Methods

BrassPlus::BrassPlus(const string & s, long an, double bal,

           double ml, double r) : Brass(s, an, bal)

{

    maxLoan = ml;

    owesBank = 0.0;

    rate = r;

}

BrassPlus::BrassPlus(const Brass & ba, double ml, double r)

           : Brass(ba)   // uses implicit copy constructor

{

    maxLoan = ml;

    owesBank = 0.0;

    rate = r;

}

// redefine how ViewAcct() works

void BrassPlus::ViewAcct() const

{

    // set up ###.## format

    format initialState = setFormat();

    precis prec = cout.precision(2);

    Brass::ViewAcct();   // display base portion

    cout << "Maximum loan: $" << maxLoan << endl;

    cout << "Owed to bank: $" << owesBank << endl;

    cout.precision(3);  // ###.### format

    cout << "Loan Rate: " << 100 * rate << "%\n";

    restore(initialState, prec);

}

// redefine how Withdraw() works

void BrassPlus::Withdraw(double amt)

{

    // set up ###.## format

    format initialState = setFormat();

    precis prec = cout.precision(2);

    double bal = Balance();

    if (amt <= bal)

        Brass::Withdraw(amt);

    else if ( amt <= bal + maxLoan - owesBank)

    {

        double advance = amt - bal;

        owesBank += advance * (1.0 + rate);

        cout << "Bank advance: $" << advance << endl;

        cout << "Finance charge: $" << advance * rate << endl;

        Deposit(advance);

        Brass::Withdraw(amt);

    }

    else

        cout << "Credit limit exceeded. Transaction cancelled.\n";

    restore(initialState, prec);

}

format setFormat()

{

    // set up ###.## format

    return cout.setf(std::ios_base::fixed,

                std::ios_base::floatfield);

}

void restore(format f, precis p)

{

    cout.setf(f, std::ios_base::floatfield);

    cout.precision(p);

}

Before looking at details of Listing 13.8, such as handling of formatting in some of the methods, let’s examine the aspects that relate directly to inheritance. Keep in mind that the derived class does not have direct access to private base-class data; the derived class has to use base-class public methods to access that data. The means of access depends on the method. Constructors use one technique, and other member functions use a different technique.

The technique that derived-class constructors use to initialize base-class private data is the member initializer list syntax. The RatedPlayer class constructors use that technique, and so do the BrassPlus constructors:

BrassPlus::BrassPlus(const string & s, long an, double bal,

           double ml, double r) : Brass(s, an, bal)

{

    maxLoan = ml;

    owesBank = 0.0;

    rate = r;

}

BrassPlus::BrassPlus(const Brass & ba, double ml, double r)

           : Brass(ba)   // uses implicit copy constructor

{

    maxLoan = ml;

    owesBank = 0.0;

    rate = r;

}

Each of these constructors uses the member initializer list syntax to pass base-class information to a base-class constructor and then uses the constructor body to initialize the new data items added by the BrassPlus class.

Non-constructors can’t use the member initializer list syntax. But a derived-class method can call a public base-class method. For instance, ignoring the formatting aspect, the core of the BrassPlus version of ViewAcct() is this:

// redefine how ViewAcct() works

void BrassPlus::ViewAcct() const

{

...

    Brass::ViewAcct();   // display base portion

    cout << "Maximum loan: $" << maxLoan << endl;

    cout << "Owed to bank: $" << owesBank << endl;

    cout << "Loan Rate: " << 100 * rate << "%\n";

...

}

In other words, BrassPlus::ViewAcct() displays the added BrassPlus data members and calls on the base-class method Brass::ViewAcct() to display the base-class data members. Using the scope-resolution operator in a derived-class method to invoke a base-class method is a standard technique.

It’s vital that the code use the scope-resolution operator. Suppose that, instead, you wrote the code this way:

// redefine erroneously how ViewAcct() works

void BrassPlus::ViewAcct() const

{

...

    ViewAcct();   // oops! recursive call

...

}

If the code doesn’t use the scope-resolution operator, the compiler assumes that ViewAcct() is BrassPlus::ViewAcct(), and this creates a recursive function that has no termination—not a good thing.

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

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

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

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