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

1. The Wine class has a string class object member (see Chapter 4) that holds the name of a wine and a Pair object (as discussed in this chapter) of valarray objects (as discussed in this chapter). The first member of each Pair object holds the vintage years, and the second member holds the numbers of bottles owned for the corresponding particular vintage year. For example, the first valarray object of the Pair object might hold the years 1988, 1992, and 1996, and the second valarray object might hold the bottle counts 24, 48, and 144. It may be convenient for Wine to have an int member that stores the number of years. Also some typedefs might be useful to simplify the coding:

typedef std::valarray ArrayInt;

typedef Pair PairArray;

Thus, the PairArray type represents type Pair, std::valarray >. Implement the Wine class by using containment. The class should have a default constructor and at least the following constructors:

// initialize label to l, number of years to y,

// vintage years to yr[], bottles to bot[]

Wine(const char * l, int y, const int yr[], const int bot[]);

// initialize label to l, number of years to y,

// create array objects of length y

Wine(const char * l, int y);

The Wine class should have a method GetBottles() that, given a Wine object with y years, prompts the user to enter the corresponding number of vintage years and bottle counts. A method Label() should return a reference to the wine name. A method sum() should return the total number of bottles in the second valarray object in the Pair object.

The program should prompt the user to enter a wine name, the number of elements of the array, and the year and bottle count information for each array element. The program should use this data to construct a Wine object and then display the information stored in the object. For guidance, here’s a sample test program:

// pe14-1.cpp  -- using Wine class with containment

#include

#include "winec.h"

int main ( void )

{

    using std::cin;

    using std::cout;

    using std::endl;

    cout << "Enter name of wine: ";

    char lab[50];

    cin.getline(lab, 50);

    cout << "Enter number of years: ";

    int yrs;

    cin >> yrs;

    Wine holding(lab, yrs); // store label, years, give arrays yrs elements

    holding.GetBottles();   // solicit input for year, bottle count

    holding.Show();         // display object contents

    const int YRS = 3;

    int y[YRS] = {1993, 1995, 1998};

    int b[YRS] = { 48, 60, 72};

    // create new object, initialize using data in arrays y and b

    Wine more("Gushing Grape Red",YRS, y, b);

    more.Show();

    cout << "Total bottles for " << more.Label() // use Label() method

         << ": " << more.sum() << endl;          // use sum() method

    cout << "Bye\n";

    return 0;

}

And here’s some sample output:

Enter name of wine: Gully Wash

Enter number of years: 4

Enter Gully Wash data for 4 year(s):

Enter year: 1988

Enter bottles for that year: 42

Enter year: 1994

Enter bottles for that year: 58

Enter year: 1998

Enter bottles for that year: 122

Enter year: 2001

Enter bottles for that year: 144

Wine: Gully Wash

        Year    Bottles

        1988    42

        1994    58

        1998    122

        2001    144

Wine: Gushing Grape Red

        Year    Bottles

        1993    48

        1995    60

        1998    72

Total bottles for Gushing Grape Red: 180

Bye

2. This exercise is the same as Programming Exercise 1, except that you should use private inheritance instead of containment. Again, a few typedefs might prove handy. Also you might contemplate the meaning of statements such as the following:

PairArray::operator=(PairArray(ArrayInt(),ArrayInt()));

cout  << (const string &)(*this);

The class should work with the same test program as shown in Programming Exercise 1.

3. Define a QueueTp template. Test it by creating a queue of pointers-to-Worker (as defined in Listing 14.10) and using the queue in a program similar to that in Listing 14.12.

4. A Person class holds the first name and the last name of a person. In addition to its constructors, it has a Show() method that displays both names. A Gunslinger class derives virtually from the Person class. It has a Draw() member that returns a type double value representing a gunslinger’s draw time. The class also has an int member representing the number of notches on a gunslinger’s gun. Finally, it has a Show() function that displays all this information.

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

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

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

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