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

This method of having the derived method call the base method works well enough for single inheritance. For example, suppose that the HeadWaiter class derives from the Waiter class. You could use a sequence of definitions like this, with each derived class adding to the information displayed by its base class:

void Worker::Show() const

{

    cout << "Name: " << fullname << "\n";

    cout << "Employee ID: " << id << "\n";

}

void Waiter::Show() const

{

    Worker::Show();

    cout << "Panache rating: " << panache << "\n";

}

void HeadWaiter::Show() const

{

    Waiter::Show();

    cout << "Presence rating: " << presence << "\n";

}

This incremental approach fails for the SingingWaiter case, however. The following method fails because it ignores the Waiter component:

void SingingWaiter::Show()

{

    Singer::Show();

}

You can remedy that by calling the Waiter version also:

void SingingWaiter::Show()

{

      Singer::Show();

      Waiter::Show();

}

However, this displays a person’s name and ID twice because Singer::Show() and with Waiter::Show() both call Worker::Show().

How can you fix this? One way is to use a modular approach instead of an incremental approach. That is, you can provide a method that displays only Worker components, another method that displays only Waiter components (instead of Waiter plus Worker components), and another that displays only Singer components. Then the SingingWaiter::Show() method can put those components together. For example, you could use this:

void Worker::Data() const

{

    cout << "Name: " << fullname << "\n";

    cout << "Employee ID: " << id << "\n";

}

void Waiter::Data() const

{

    cout << "Panache rating: " << panache << "\n";

}

void Singer::Data() const

{

    cout << "Vocal range: " << pv[voice] << "\n";

}

void SingingWaiter::Data() const

{

    Singer::Data();

    Waiter::Data();

}

void SingingWaiter::Show() const

{

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

    Worker::Data();

    Data();

}

Similarly, the other Show() methods would be built from the appropriate Data() components.

With this approach, objects would still use the Show() method publicly. The Data() methods, on the other hand, should be internal to the classes; they should be helper methods used to facilitate the public interface. However, making the Data() methods private would prevent, say, Waiter code from using Worker::Data(). Here is just the kind of situation for which the protected access class is useful. If the Data() methods are protected, they can by used internally by all the classes in the hierarchy while being kept hidden from the outside world.

Another approach would be to make all the data components protected instead of private, but using protected methods instead of protected data puts tighter control on the allowable access to the data.

The Set() methods, which solicit data for setting object values, present a similar problem. For example, SingingWaiter::Set()should ask for Worker information once, not twice. The same solution used for Show() works. You can provide protected Get() methods that solicit information for just a single class, and then you can put together Set() methods that use the Get() methods as building blocks.

In short, introducing MI with a shared ancestor requires introducing virtual base classes, altering the rules for constructor initialization lists, and possibly recoding the classes if they were written with MI in mind. Listing 14.10 shows the modified class declarations with these changes institutes, and Listing 14.11 shows the implementation.

Listing 14.10. workermi.h

// workermi.h  -- working classes with MI

#ifndef WORKERMI_H_

#define WORKERMI_H_

#include

class Worker   // an abstract base class

{

private:

    std::string fullname;

    long id;

protected:

    virtual void Data() const;

    virtual void Get();

public:

    Worker() : fullname("no one"), id(0L) {}

    Worker(const std::string & s, long n)

            : fullname(s), id(n) {}

    virtual ~Worker() = 0; // pure virtual function

    virtual void Set() = 0;

    virtual void Show() const = 0;

};

class Waiter : virtual public Worker

{

private:

    int panache;

protected:

    void Data() const;

    void Get();

public:

    Waiter() : Worker(), panache(0) {}

    Waiter(const std::string & s, long n, int p = 0)

            : Worker(s, n), panache(p) {}

    Waiter(const Worker & wk, int p = 0)

            : Worker(wk), panache(p) {}

    void Set();

    void Show() const;

};

class Singer : virtual public Worker

{

protected:

enum {other, alto, contralto, soprano,

                    bass, baritone, tenor};

    enum {Vtypes = 7};

    void Data() const;

    void Get();

private:

    static char *pv[Vtypes];    // string equivs of voice types

    int voice;

public:

    Singer() : Worker(), voice(other) {}

    Singer(const std::string & s, long n, int v = other)

            : Worker(s, n), voice(v) {}

    Singer(const Worker & wk, int v = other)

            : Worker(wk), voice(v) {}

    void Set();

    void Show() const;

};

// multiple inheritance

class SingingWaiter : public Singer, public Waiter

{

protected:

    void Data() const;

    void Get();

public:

    SingingWaiter()  {}

    SingingWaiter(const std::string & s, long n, int p = 0,

                            int v = other)

            : Worker(s,n), Waiter(s, n, p), Singer(s, n, v) {}

    SingingWaiter(const Worker & wk, int p = 0, int v = other)

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

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

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

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