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

        if( ps = dynamic_cast(pg))

            ps->Say();

    }

    return 0;

}

Grand * GetOne()    // generate one of three kinds of objects randomly

{

    Grand * p;

    switch( std::rand() % 3)

    {

        case 0: p = new Grand(std::rand() % 100);

                    break;

        case 1: p = new Superb(std::rand() % 100);

                    break;

        case 2: p = new Magnificent(std::rand() % 100,

                              'A' + std::rand() % 26);

                    break;

    }

    return p;

}

Note

Even if your compiler supports RTTI, it might have that feature turned off by default. If the feature is inactive, the program may still compile but produce runtime errors. If you find this to be the case, you should check your documentation or explore the menu options.

The program in Listing 15.17 illustrates an important point. You should use virtual functions when possible and RTTI only when necessary. Here is some sample output:

I am a superb class!!

I hold the superb value of 68!

I am a magnificent class!!!

I hold the character R and the integer 68!

I am a magnificent class!!!

I hold the character D and the integer 12!

I am a magnificent class!!!

I hold the character V and the integer 59!

I am a grand class!

As you can see, the Say() methods were invoked just for the Superb and Magnificent classes. (The output will vary from run to run because the program uses rand() to select the object type.)

You can use dynamic_cast with references, too. The usage is slightly different; there is no reference value corresponding to the null-pointer type, so there’s no special reference value that can be used to indicate failure. Instead, when goaded by an improper request, dynamic_cast throws a type bad_cast exception, which is derived from the exception class and defined in the typeinfo header file. Thus, the operator can be used as follows, where rg is a reference to a Grand object:

#include // for bad_cast

...

try {

    Superb & rs = dynamic_cast(rg);

    ...

}

catch(bad_cast &){

    ...

};

The typeid Operator and type_info Class

The typeid operator lets you determine whether two objects are the same type. Somewhat like sizeof, it accepts two kinds of arguments:

• The name of a class

• An expression that evaluates to an object

The typeid operator returns a reference to a type_info object, where type_info is a class defined in the typeinfo header file (formerly typeinfo.h). The type_info class overloads the == and != operators so that you can use these operators to compare types. For example, the following expression evaluates to the bool value true if pg points to a Magnificent object and to false otherwise:

typeid(Magnificent) == typeid(*pg)

If pg happens to be a null pointer, the program throws a bad_typeid exception. This exception type is derived from the exception class and is declared in the typeinfo header file.

The implementation of the type_info class varies among vendors, but it includes a name() member that returns an implementation-dependent string that is typically (but not necessarily) the name of the class. For example, the following statement displays the string defined for the class of the object to which the pointer pg points:

cout << "Now processing type " << typeid(*pg).name() << ".\n";

Listing 15.18 modifies Listing 15.17 so that it uses the typeid operator and the name() member function. Note that they are used for situations that dynamic_cast and virtual functions don’t handle. The typeid test is used to select an action that isn’t even a class method, so it can’t be invoked by a class pointer. The name() method statement shows how the method can be used in debugging. Note that the program includes the typeinfo header file.

Listing 15.18. rtti2.cpp

// rtti2.cpp  -- using dynamic_cast, typeid, and type_info

#include

#include

#include

#include

using namespace std;

class Grand

{

private:

    int hold;

public:

    Grand(int h = 0) : hold(h) {}

    virtual void Speak() const { cout << "I am a grand class!\n";}

    virtual int Value() const { return hold; }

};

class Superb : public Grand

{

public:

    Superb(int h = 0) : Grand(h) {}

    void Speak() const {cout << "I am a superb class!!\n"; }

    virtual void Say() const

        { cout << "I hold the superb value of " << Value() << "!\n";}

};

class Magnificent : public Superb

{

private:

    char ch;

public:

    Magnificent(int h = 0, char cv = 'A') : Superb(h), ch(cv) {}

    void Speak() const {cout << "I am a magnificent class!!!\n";}

    void Say() const {cout << "I hold the character " << ch <<

               " and the integer "  << Value() << "!\n"; }

};

Grand * GetOne();

int main()

{

    srand(time(0));

    Grand * pg;

    Superb * ps;

    for (int i = 0; i < 5; i++)

    {

        pg = GetOne();

        cout << "Now processing type " << typeid(*pg).name() << ".\n";

        pg->Speak();

        if( ps = dynamic_cast(pg))

            ps->Say();

        if (typeid(Magnificent) == typeid(*pg))

            cout << "Yes, you're really magnificent.\n";

    }

    return 0;

}

Grand * GetOne()

{

    Grand * p;

    switch( rand() % 3)

    {

        case 0: p = new Grand(rand() % 100);

                    break;

        case 1: p = new Superb(rand() % 100);

                    break;

        case 2: p = new Magnificent(rand() % 100, 'A' + rand() % 26);

                    break;

    }

    return p;

}

Here’s a sample run of the program in Listing 15.18:

Now processing type Magnificent.

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

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

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

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