tailieunhanh - A Complete Guide to Programming in C++ part 57

A Complete Guide to Programming in C++ part 57. This book provides both novice and experienced programmers with a comprehensive resource manual for the C++ programming language. Readers gain experience in all aspects of programming, from elementary language concepts to professional software development, with in depth coverage of all the language elements en route. These elements are carefully ordered to help the reader create useful programs every step of the way. | EXERCISE 539 Exercise The class hierarchy representing a supermarket chain s checkout system comprises the base class Product and the derived classes PrepackedFood and job is to test various cast techniques for this class see also Exercise 3 in Chapter 23 . Define a global function isLowerCode that determines which one of two products has the lower barcode and returns a reference to the product with the lower barcode. Define an array with three pointers to the base class Product. Dynamically create one object each of the types Product PrepackedFood and three objects are to be referenced by the array pointers. Additionally define a pointer to the derived class FreshFood. Initialize the pointer with the address of a dynamically allocated object of the same class. Now call the method printer for all four version of printer is executed Perform downcasting to execute the correct version of printer in every case. Display the pointer values before and after downcasting. Use the pointer of the derived class FreshFood to call the base class version of printer . Perform an appropriate upcast. Test the function isLowerCode by multiple calls to the function with various arguments. Output the product with the lower barcode value in each case. 540 CHAPTER 24 TYPE CONVERSION IN CLASS HIERARCHIES SOLUTION ----------------------------------------------- o Defines the classes Product PrepackedFood and FreshFood --------------------------------------------------------------- Unchanged See the previous chapter s solutions. -------------------------------------------------- Tests up and down casts for the classes Product PrepackedFood and FreshFood. -------------------------------------------------- include const Product isLowerCode const Product pl const Product p2 int main Product pv 3 FreshFood pu pv 0 new Product 12345L Flour pv 1 new PrepackedFood 23456 Salt pv 2 new FreshFood 98765 Grapes pu

TỪ KHÓA LIÊN QUAN