Horton2014_Book_BeginningCPlusPlus.pdf

Full Transcript

For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to access them. Contents at a Glance About the Author xxiii About the Technical Reviewer xxv Introduction xxvii Chapter 1: Basic Ideas...

For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to access them. Contents at a Glance About the Author xxiii About the Technical Reviewer xxv Introduction xxvii Chapter 1: Basic Ideas 1 Chapter 2: Introducing Fundamental Types of Data  23 Chapter 3: Working with Fundamental Data Types 55 Chapter 4: Making Decisions 79 Chapter 5: Arrays and Loops 105 Chapter 6: Pointers and References 151 Chapter 7: Working with Strings 185 Chapter 8: Defining Functions 213 Chapter 9: Lambda Expressions 271 Chapter 10: Program Files and Preprocessing Directives 287 Chapter 11: Defining Your Own Data Types 315 Chapter 12: Operator Overloading 365 Chapter 13: Inheritance 399 Chapter 14: Polymorphism 429 v Contents at a Glance Chapter 15: Runtime Errors and Exceptions 463 Chapter 16: Class Templates 495 Chapter 17: File Input and Output 533 Index 593 vi Introduction Welcome to Beginning C++. This is a revised and updated version of my previous book, Beginning ANSI C++. The C++ language has been extended and improved considerably since the previous book, so much so that it was no longer possible to squeeze detailed explanations of all of C++ in a single book. This tutorial will teach enough of the essential C++ language and Standard Library features to enable you to write your own C++ applications. With the knowledge from this book you should have no difficulty in extending the depth and scope of your C++ expertise. C++ is much more accessible than many people assume. I have assumed no prior programming knowledge. If you are keen to learn and have an aptitude for thinking logically, getting a grip on C++ will be easier than you might imagine. By developing C++ skills, you’ll be learning a language that is already used by millions, and that provides the capability for application development in just about any context. The C++ language in this book corresponds to the latest ISO standard, commonly referred to as C++ 14. C++ 14 is a minor extension over the previous standard, C++ 11, so there is very little in the book that is C++ 14 specific. All the examples in the book can be compiled and executed using C++ 11-conforming compilers that are available now. Using the Book To learn C++ with this book, you’ll need a compiler that conforms reasonably well to the C++ 11 standard and a text editor suitable for working with program code. There are several compilers available currently that are reasonably C++ 11 compliant, some of which are free. The GCC compiler that is produced by the GNU Project has comprehensive support for C++ 11 and it is open source and free to download. Installing GCC and putting it together with a suitable editor can be a little tricky if you are new to this kind of thing. An easy way to install GCC along with a suitable editor is to download Code::Blocks from http://www.codeblocks.org. Code::Blocks is a free IDE for Linux, Apple Mac OS X, and Microsoft Windows. It supports program development using several compilers including compilers for GCC, Clang, and open Watcom. This implies you get support for C, C++, and Fortran. Another possibility is to use Microsoft Visual C++ that runs under Microsoft Windows. It is not fully compliant with C++ 11, but it’s getting there. The free version is available as Microsoft Visual Studio 2013 Express and at the time of writing this will compile most of the examples, and should compile them all eventually. You can download it from http://www.microsoft.com/en-us/download/details.aspx?id=43733. While the Microsoft Visual C++ compiler is more limited than GCC, in terms of the extent to which C++ 11 is supported, you get a professional editor and support for other languages such as C# and Basic. Of course, you can always install both! There are other compilers that support C++ 11, which you can find with a quick online search. I’ve organized the material in this book to be read sequentially, so you should start at the beginning and keep going until you reach the end. However, no one ever learned programming by just reading a book. You’ll only learn how to program in C++ by writing code, so make sure you key in all the examples—don’t just copy them from the download files—and compile and execute the code that you’ve keyed in. This might seem tedious at times, but it’s surprising how much just typing in C++ statements will help your understanding, especially when you may feel you’re struggling with some of the ideas. If an example doesn’t work, resist the temptation to go straight back to the book to see why. Try to figure out from your code what is wrong. This is good practice for what you’ll have to do when you are developing C++ applications for real. xxvii Introduction Making mistakes is a fundamental part of the learning process and the exercises should provide you with ample opportunity for that. It’s a good idea to dream up a few exercises of your own. If you are not sure about how to do something, just have a go before looking it up. The more mistakes you make, the greater the insight you’ll have into what can, and does, go wrong. Make sure you attempt all the exercises, and remember, don’t look at the solutions until you’re sure that you can’t work it out yourself. Most of these exercises just involve a direct application of what’s covered in a chapter—they’re just practice, in other words—but some also require a bit of thought or maybe even inspiration. I wish you every success with C++. Above all, enjoy it! —Ivor Horton xxviii Chapter 1 Basic Ideas I’ll sometimes have to make use of things in examples before I have explained them in detail. This chapter is intended to help when this occurs by giving you an overview of the major elements of C++ and how they hang together. I’ll also explain a few concepts relating to the representation of numbers and characters in your computer. In this chapter you’ll learn: What is meant by Modern C++ The elements of a C++ program How to document your program code How your C++ code becomes an executable program How object-oriented programming differs from procedural programming What binary, hexadecimal, and octal number systems are What Unicode is Modern C++ Modern C++ is programming using of the features of the latest and greatest incarnation of C++. This is the C++ language defined by the C++ 11 standard, which is being modestly extended and improved by the latest standard, C++ 14. This book relates to C++ as defined by C++14. There’s no doubt that C++ is the most widely used and most powerful programming language in the world today. If you were just going to learn one programing language, C++ is the ideal choice. It is effective for developing applications across an enormous range of computing devices and environments: for personal computers, workstations, mainframe computers, tablets, and mobile phones. Just about any kind of program can be written in C++ from device drivers to operating systems, from payroll and administrative programs to games. C++ compilers are available widely too. There are up-to-date compilers that run on PCs, workstations, and mainframes, often with cross-compiling capabilities, where you can develop the code in one environment and compile it to execute in another. C++ comes with a very extensive Standard Library. This is a huge collection of routines and definitions that provide functionality that is required by many programs. Examples are numerical calculations, string processing, sorting and searching, organizing and managing data, and input and output. The Standard Library is so vast that we will only scratch the surface of what is available in this book. It really needs several books to fully elaborate all the capability it provides. Beginning STL is a companion book that is a tutorial on using the Standard Template Library, which is the subset of the C++ Standard Library for managing and processing data in various ways. 1 Chapter 1 Basic Ideas Given the scope of the language and the extent of the library, it’s not unusual for a beginner to find C++ somewhat daunting. It is too extensive to learn in its entirety from a single book. However, you don’t need to learn all of C++ to be able to write substantial programs. You can approach the language step by step, in which case it really isn’t difficult. An analogy might be learning to drive a car. You can certainly become a very competent and safe driver without necessarily having the expertise, knowledge, and experience to drive in the Indianapolis 500. With this book you can learn everything you need to program effectively in C++. By the time you reach the end, you’ll be confidently writing your own applications. You’ll also be well equipped to explore the full extent of C++ and its Standard Library. C++ Program Concepts There will be much more detail on everything I discuss in this section later in the book. I’ll jump straight in with the complete, fully working, C++ program shown in Figure 1-1, which explains what the various bits of it are. I’ll use the example as a base for discussing some more general aspects of C++. This is a statement. Statements end with a semicolon. There is also a comment on this line. // Ex1_01.cpp These two lines are comments. // A complete C++ program Comments begin with // #include This line adds input/output capability. int main ( ) This is the first line of the function main. { int answer {42}; // Defines answer with value 42 std::cout answer; if (toupper(answer) == 'N') break; } double total{}; size_t count{}; day = 1; std::cout value) result = value; return result; } You need the compare.h header file to be included so that the namespace is identified. This tells the compiler to deduce that the functions are declared within the namespace. There's an #include directive for the vector header that is also included into compare.h. The contents of the vector header will only appear once in this file because all the Standard Library headers have preprocessing directives to prevent duplication. It's a good idea in general to have #include directives for every header that a file uses, even when one header may include another header that you use. This makes the file independent of potential changes to the header files. Of course you could place the code for the function definitions within the compare namespace directly. In this case, the contents of compare.cpp would be: #include namespace compare { double max(const std::vector& data) { // Code for max() as above... } double min(const std::vector& data) { // Code for min() as above... } } 299 Chapter 10 Program Files and Preprocessing Directives If you write the function definitions in this way, then you don’t need to #include compare.h into this file. This is because the definitions are within the namespace. Using the functions is the same, however you have defined them. To confirm how easy it is, let’s try it out with the functions that you’ve just defined. Create the compare.h header file with the contents I discussed earlier. Create the first version of compare.cpp where the definitions are not defined in a namespace block. All you need now is a.cpp file containing the definition of main() to try the functions out: // Ex10_02.cpp // Using functions in a namespace #include #include #include "compare.h" using compare::max; // Using declaration for max using compare::min; // Using declaration for min int main() { std::vector data {1.5, 4.6, 3.1, 1.1, 3.8, 2.1}; std::cout 0) length = lv; return this; } Box* Box::setWidth(double wv) { if(wv > 0) width = wv; return this; } Box* Box::setHeight(double hv) { if(hv > 0) height = hv; return this; } Now you can modify all the dimensions of a Box object in a single statement: Box aBox {10.0,15.0,25.0}; // Create a box aBox.setLength(20.0)->setWidth(40.0)->setHeight(10.0); // Set all dimensions of aBox Because the mutator functions return the this pointer, you can use the value returned by one function to call the next. Thus the pointer returned by setLength() is used to call setWidth(), which returns a pointer you can use to call setHeight(). Isn’t that nice? const Objects and const Member Functions Let’s look again at the volume() function member of the Box class in Ex11_03. Suppose you change the code in main() so that box1 is const: const Box box1 {2.0, 3.0, 4.0}; // A box that is a constant Box box2 {5.0}; // A box that is a cube std::cout getNext(); // Save the next package if (pPackage) // If there is one... { pCurrent = pPackage; // Update current to the next return pPackage->getBox(); } pCurrent = nullptr; // If we get to here... return nullptr; //...there was no next } 356 Chapter 11 Defining Your Own Data Types When pCurrent contains the address of a Package object, you call its getNext() member to obtain the address of the next Package object and save it in pPackage. If pCurrent is nullptr, then the first in the list is obtained and returned by calling getFirstBox(). If the pointer to the next Package object, pPackage, is not nullptr, it is stored in pCurrent and the Box pointer it contains is returned. If pPackage is nullptr, the end of the list has been reached so pCurrent is reset to nullptr and nullptr is returned. Because nullptr is returned to signal there is no next pointer to a Box, we cannot return a reference. The member to list the contents of the Truckload object can be implemented like this: void Truckload::listBoxes() { pCurrent = pHead; size_t count {}; while (pCurrent) { pCurrent->getBox()->listBox(); pCurrent = pCurrent->getNext(); if(! (++count % 5)) std::cout pNext; return pHead->pBox; } The function to obtain the address of the next Box object in the list can now be defined as: ptr Truckload::getNextBox() { if (!pCurrent) // If there's no current... return getFirstBox(); //...return the 1st auto pPackage = pCurrent->pNext; // Save the next package if (pPackage) // If there is one... { pCurrent = pPackage; // Update current to the next return pPackage->pBox; } pCurrent = nullptr; // If we get to here... return nullptr; //...there was no next } Finally the listBoxes() member of Truckload will be: void Truckload::listBoxes() { pCurrent = pHead; size_t count {}; while (pCurrent) { pCurrent->pBox->listBox(); pCurrent = pCurrent->pNext; if(! (++count % 5)) std::cout

Use Quizgecko on...
Browser
Browser