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

            : Worker(wk), Waiter(wk,p), Singer(wk,v) {}

    SingingWaiter(const Waiter & wt, int v = other)

            : Worker(wt),Waiter(wt), Singer(wt,v) {}

    SingingWaiter(const Singer & wt, int p = 0)

            : Worker(wt),Waiter(wt,p), Singer(wt) {}

    void Set();

    void Show() const;

};

#endif

Listing 14.11. workermi.cpp

// workermi.cpp -- working class methods with MI

#include "workermi.h"

#include

using std::cout;

using std::cin;

using std::endl;

// Worker methods

Worker::~Worker() { }

// protected methods

void Worker::Data() const

{

    cout << "Name: " << fullname << endl;

    cout << "Employee ID: " << id << endl;

}

void Worker::Get()

{

    getline(cin, fullname);

    cout << "Enter worker's ID: ";

    cin >> id;

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

        continue;

}

// Waiter methods

void Waiter::Set()

{

    cout << "Enter waiter's name: ";

    Worker::Get();

    Get();

}

void Waiter::Show() const

{

    cout << "Category: waiter\n";

    Worker::Data();

    Data();

}

// protected methods

void Waiter::Data() const

{

    cout << "Panache rating: " << panache << endl;

}

void Waiter::Get()

{

    cout << "Enter waiter's panache rating: ";

    cin >> panache;

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

        continue;

}

// Singer methods

char * Singer::pv[Singer::Vtypes] = {"other", "alto", "contralto",

            "soprano", "bass", "baritone", "tenor"};

void Singer::Set()

{

    cout << "Enter singer's name: ";

    Worker::Get();

    Get();

}

void Singer::Show() const

{

    cout << "Category: singer\n";

    Worker::Data();

    Data();

}

// protected methods

void Singer::Data() const

{

    cout << "Vocal range: " << pv[voice] << endl;

}

void Singer::Get()

{

    cout << "Enter number for singer's vocal range:\n";

    int i;

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

    {

        cout << i << ": " << pv[i] << "   ";

        if ( i % 4 == 3)

            cout << endl;

    }

    if (i % 4 != 0)

        cout << '\n';

    cin >>  voice;

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

        continue;

}

// SingingWaiter methods

void SingingWaiter::Data() const

{

    Singer::Data();

    Waiter::Data();

}

void SingingWaiter::Get()

{

    Waiter::Get();

    Singer::Get();

}

void SingingWaiter::Set()

{

    cout << "Enter singing waiter's name: ";

    Worker::Get();

    Get();

}

void SingingWaiter::Show() const

{

    cout << "Category: singing waiter\n";

    Worker::Data();

    Data();

}

Of course, curiosity demands that you test these classes, and Listing 14.12 provides code to do so. Note that the program makes use of polymorphism by assigning the addresses of various kinds of classes to base-class pointers. Also the program uses the C-style string library function strchr() in the following test:

while (strchr("wstq", choice) == NULL)

This function returns the address of the first occurrence of the choice character value in the string "wstq"; the function returns the NULL pointer if the character isn’t found. This test is simpler to write than an if statement that compares choice to each letter individually.

Be sure to compile Listing 14.12 along with workermi.cpp.

Listing 14.12. workmi.cpp

// workmi.cpp -- multiple inheritance

// compile with workermi.cpp

#include

#include

#include "workermi.h"

const int SIZE = 5;

int main()

{

   using std::cin;

   using std::cout;

   using std::endl;

   using std::strchr;

   Worker * lolas[SIZE];

    int ct;

    for (ct = 0; ct < SIZE; ct++)

    {

        char choice;

        cout << "Enter the employee category:\n"

            << "w: waiter  s: singer  "

            << "t: singing waiter  q: quit\n";

        cin >> choice;

        while (strchr("wstq", choice) == NULL)

        {

            cout << "Please enter a w, s, t, or q: ";

            cin >> choice;

        }

        if (choice == 'q')

            break;

        switch(choice)

        {

            case 'w':   lolas[ct] = new Waiter;

                        break;

            case 's':   lolas[ct] = new Singer;

                        break;

            case 't':   lolas[ct] = new SingingWaiter;

                        break;

        }

        cin.get();

        lolas[ct]->Set();

    }

    cout << "\nHere is your staff:\n";

    int i;

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

    {

        cout << endl;

        lolas[i]->Show();

    }

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

        delete lolas[i];

    cout << "Bye.\n";

    return 0;

}

Here is a sample run of the program in Listings 14.10, 14.11, and 14.12:

Enter the employee category:

w: waiter  s: singer  t: singing waiter  q: quit

w

Enter waiter's name: Wally Slipshod

Enter worker's ID: 1040

Enter waiter's panache rating: 4

Enter the employee category:

w: waiter  s: singer  t: singing waiter  q: quit

s

Enter singer's name: Sinclair Parma

Enter worker's ID: 1044

Enter number for singer's vocal range:

0: other   1: alto   2: contralto   3: soprano

4: bass   5: baritone   6: tenor

5

Enter the employee category:

w: waiter  s: singer  t: singing waiter  q: quit

t

Enter singing waiter's name: Natasha Gargalova

Enter worker's ID: 1021

Enter waiter's panache rating: 6

Enter number for singer's vocal range:

0: other   1: alto   2: contralto   3: soprano

4: bass   5: baritone   6: tenor

3

Enter the employee category:

w: waiter  s: singer  t: singing waiter  q: quit

q

Here is your staff:

Category: waiter

Name: Wally Slipshod

Employee ID: 1040

Panache rating: 4

Category: singer

Name: Sinclair Parma

Employee ID: 1044

Vocal range: baritone

Category: singing waiter

Name: Natasha Gargalova

Employee ID: 1021

Vocal range: soprano

Panache rating: 6

Bye.

Let’s look at a few more matters concerning MI.

Mixed Virtual and Nonvirtual Bases

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

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

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

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