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

Listing 10.5 provides the method definitions for the stock program. It includes the stock10.h file in order to provide the class declaration. (Recall that enclosing the filename in double quotation marks instead of in brackets causes the compiler to search for it at the same location where your source files are located.) Also Listing 10.5 includes the iostream header file to provide I/O support. The listing also provides using declarations and qualified names (such as std::string) to provide access to various declarations in the header files. This file adds the constructor and destructor method definitions to the prior methods. To help you see when these methods are called, they each display a message. This is not a usual feature of constructors and destructors, but it can help you better visualize how classes use them.

Listing 10.5. stock10.cpp

// stock10.cpp -- Stock class with constructors, destructor added

#include

#include "stock10.h"

// constructors (verbose versions)

Stock::Stock()        // default constructor

{

    std::cout << "Default constructor called\n";

    company = "no name";

    shares = 0;

    share_val = 0.0;

    total_val = 0.0;

}

Stock::Stock(const std::string & co, long n, double pr)

{

    std::cout << "Constructor using " << co << " called\n";

    company = co;

    if (n < 0)

    {

        std::cout << "Number of shares can't be negative; "

                   << company << " shares set to 0.\n";

        shares = 0;

    }

    else

        shares = n;

    share_val = pr;

    set_tot();

}

// class destructor

Stock::~Stock()        // verbose class destructor

{

    std::cout << "Bye, " << company << "!\n";

}

// other methods

void Stock::buy(long num, double price)

{

     if (num < 0)

    {

        std::cout << "Number of shares purchased can't be negative. "

             << "Transaction is aborted.\n";

    }

    else

    {

        shares += num;

        share_val = price;

        set_tot();

    }

}

void Stock::sell(long num, double price)

{

    using std::cout;

    if (num < 0)

    {

        cout << "Number of shares sold can't be negative. "

             << "Transaction is aborted.\n";

    }

    else if (num > shares)

    {

        cout << "You can't sell more than you have! "

             << "Transaction is aborted.\n";

    }

    else

    {

        shares -= num;

        share_val = price;

        set_tot();

    }

}

void Stock::update(double price)

{

    share_val = price;

    set_tot();

}

void Stock::show()

{

    using std::cout;

    using std::ios_base;

    // set format to #.###

    ios_base::fmtflags orig =

        cout.setf(ios_base::fixed, ios_base::floatfield);

    std::streamsize prec = cout.precision(3);

    cout << "Company: " << company

        << "  Shares: " << shares << '\n';

    cout << "  Share Price: $" << share_val;

    // set format to #.##

    cout.precision(2);

    cout << "  Total Worth: $" << total_val << '\n';

    // restore original format

    cout.setf(orig, ios_base::floatfield);

    cout.precision(prec);

}

A Client File

Listing 10.6 provides a short program for testing the new methods in the stock program. Because it simply uses the Stock class, this listing is a client of the Stock class. Like stock10.cpp, it includes the stock10.h file to provide the class declaration. The program demonstrates constructors and destructors. It also uses the same formatting commands invoked by Listing 10.3. To compile the complete program, you use the techniques for multifile programs described in Chapters 1 and 9.

Listing 10.6. usestok1.cpp

// usestok1.cpp -- using the Stock class

// compile with stock10.cpp

#include

#include "stock10.h"

int main()

{

  {

    using std::cout;

    cout << "Using constructors to create new objects\n";

    Stock stock1("NanoSmart", 12, 20.0);            // syntax 1

    stock1.show();

    Stock stock2 = Stock ("Boffo Objects", 2, 2.0); // syntax 2

    stock2.show();

    cout << "Assigning stock1 to stock2:\n";

    stock2 = stock1;

    cout << "Listing stock1 and stock2:\n";

    stock1.show();

    stock2.show();

    cout << "Using a constructor to reset an object\n";

    stock1 = Stock("Nifty Foods", 10, 50.0);    // temp object

    cout << "Revised stock1:\n";

    stock1.show();

    cout << "Done\n";

  }

    return 0;

}

Compiling the program represented by Listings 10.4, 10.5, and 10.6 produces an executable program. Here’s one compiler’s output from the executable program:

Using constructors to create new objects

Constructor using NanoSmart called

Company: NanoSmart  Shares: 12

  Share Price: $20.00  Total Worth: $240.00

Constructor using Boffo Objects called

Company: Boffo Objects  Shares: 2

  Share Price: $2.00  Total Worth: $4.00

Assigning stock1 to stock2:

Listing stock1 and stock2:

Company: NanoSmart  Shares: 12

  Share Price: $20.00  Total Worth: $240.00

Company: NanoSmart  Shares: 12

  Share Price: $20.00  Total Worth: $240.00

Using a constructor to reset an object

Constructor using Nifty Foods called

Bye, Nifty Foods!

Revised stock1:

Company: Nifty Foods  Shares: 10

  Share Price: $50.00  Total Worth: $500.00

Done

Bye, NanoSmart!

Bye, Nifty Foods!

Some compilers may produce a program with the following initial output, which has one additional line:

Using constructors to create new objects

Constructor using NanoSmart called

Company: NanoSmart  Shares: 12

  Share Price: $20.00  Total Worth: $240.00

Constructor using Boffo Objects called

Bye, Boffo Objects!                          << additional line

Company: Boffo Objects  Shares: 2

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

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

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

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