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

   Brass * p_clients[CLIENTS];


   std::string temp;


   long tempnum;


   double tempbal;


   char kind;



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


   {


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


       getline(cin,temp);


       cout << "Enter client's account number: ";


       cin >> tempnum;


       cout << "Enter opening balance: $";


       cin >> tempbal;


       cout << "Enter 1 for Brass Account or "


            << "2 for BrassPlus Account: ";


       while (cin >> kind && (kind != '1' && kind != '2'))


           cout <<"Enter either 1 or 2: ";


       if (kind == '1')


           p_clients[i] = new Brass(temp, tempnum, tempbal);


       else


       {


           double tmax, trate;


           cout << "Enter the overdraft limit: $";


           cin >> tmax;


           cout << "Enter the interest rate "


                << "as a decimal fraction: ";


           cin >> trate;


           p_clients[i] = new BrassPlus(temp, tempnum, tempbal,


                                        tmax, trate);


        }


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


            continue;


   }


   cout << endl;


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


   {


       p_clients[i]->ViewAcct();


       cout << endl;


   }



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


   {


       delete p_clients[i];  // free memory


   }


   cout << "Done.\n";


   return 0;


}


The program in Listing 13.10 lets user input determine the type of account to be added and then uses new to create and initialize an object of the proper type. You may recall that getline(cin,temp) reads a line of input from cin and stores it in the string object temp.

Here is a sample run of the program in Listing 13.10:

Enter client's name: Harry Fishsong


Enter client's account number: 112233


Enter opening balance: $1500


Enter 1 for Brass Account or 2 for BrassPlus Account: 1


Enter client's name: Dinah Otternoe


Enter client's account number: 121213


Enter opening balance: $1800


Enter 1 for Brass Account or 2 for BrassPlus Account: 2


Enter the overdraft limit: $350


Enter the interest rate as a decimal fraction: 0.12


Enter client's name: Brenda Birdherd


Enter client's account number: 212118


Enter opening balance: $5200


Enter 1 for Brass Account or 2 for BrassPlus Account: 2


Enter the overdraft limit: $800


Enter the interest rate as a decimal fraction: 0.10


Enter client's name: Tim Turtletop


Enter client's account number: 233255


Enter opening balance: $688


Enter 1 for Brass Account or 2 for BrassPlus Account: 1



Client: Harry Fishsong


Account Number: 112233


Balance: $1500.00



Client: Dinah Otternoe


Account Number: 121213


Balance: $1800.00


Maximum loan: $350.00


Owed to bank: $0.00


Loan Rate: 12.00%



Client: Brenda Birdherd


Account Number: 212118


Balance: $5200.00


Maximum loan: $800.00


Owed to bank: $0.00


Loan Rate: 10.00%



Client: Tim Turtletop


Account Number: 233255


Balance: $688.00



Done.

The polymorphic aspect is provided by the following code:

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


{


    p_clients[i]->ViewAcct();


    cout << endl;


}

If the array member points to a Brass object, Brass::ViewAcct() is invoked; if the array member points to a BrassPlus object, BrassPlus::ViewAcct() is invoked. If Brass::ViewAcct() were been declared as virtual, Brass:ViewAcct() would be invoked in all cases.

The Need for Virtual Destructors

The code in Listing 13.10 that uses delete to free the objects allocated by new illustrates why the base class should have a virtual destructor, even if no destructor appears to be needed. If the destructors are not virtual, then just the destructor corresponding to the pointer type is called. In Listing 13.10, this means that only the Brass destructor would be called, even if the pointer pointed to a BrassPlus object. If the destructors are virtual, the destructor corresponding to the object type is called. So if a pointer points to a BrassPlus object, the BrassPlus destructor is called. And when a BrassPlus destructor finishes, it automatically calls the base-class constructor. Thus, using virtual destructors ensures that the correct sequence of destructors is called. In Listing 13.10, this correct behavior isn’t essential because the destructors do nothing. But if, say, BrassPlus had a do-something destructor, it would be vital for Brass to have a virtual destructor, even if it did nothing.

Static and Dynamic Binding

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

Все книги серии 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.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

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

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