ebook img

Beginning c PDF

620 Pages·2014·6.292 MB·English
by  HortonIvor
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Beginning c

BOOKS FOR PROFESSIONALS BY PROFESSIONALS® Horton Beginning C++ RELATED Beginning C++ is a tutorial for beginners in C++ and discusses a subset of C++ that is suitable for beginners. The language syntax corresponds to the C++14 standard. This book is environment neutral and does not presume any specific operating system or program development system. There is no assumption of prior programming knowledge. All language concepts that are explained in the book are illustrated with working program examples. Most chapters include exercises for you to test your knowledge. Code downloads are provided for examples from the text and solutions to the exercises and there is an additional download for a more substantial project for you to try when you have finished the book. This book introduces the elements of the C++ standard library that provide essential support for the language syntax that is discussed. While the Standard Template Library (STL) is not discussed to a significant extent, a few elements from the STL that are important to the notion of modern C++ are introduced and applied. You’ll learn: (cid:115)(cid:0)(cid:40)(cid:79)(cid:87)(cid:0)(cid:84)(cid:79)(cid:0)(cid:87)(cid:79)(cid:82)(cid:75)(cid:0)(cid:87)(cid:73)(cid:84)(cid:72)(cid:0)(cid:70)(cid:85)(cid:78)(cid:68)(cid:65)(cid:77)(cid:69)(cid:78)(cid:84)(cid:65)(cid:76)(cid:0)(cid:35)(cid:11)(cid:11)(cid:0)(cid:68)(cid:65)(cid:84)(cid:65)(cid:0)(cid:84)(cid:89)(cid:80)(cid:69)(cid:83)(cid:0)(cid:65)(cid:78)(cid:68)(cid:0)(cid:68)(cid:79)(cid:0)(cid:67)(cid:65)(cid:76)(cid:67)(cid:85)(cid:76)(cid:65)(cid:84)(cid:73)(cid:79)(cid:78)(cid:83) (cid:115)(cid:0)(cid:40)(cid:79)(cid:87)(cid:0)(cid:84)(cid:79)(cid:0)(cid:66)(cid:85)(cid:73)(cid:76)(cid:68)(cid:0)(cid:76)(cid:79)(cid:71)(cid:73)(cid:67)(cid:0)(cid:73)(cid:78)(cid:84)(cid:79)(cid:0)(cid:65)(cid:0)(cid:80)(cid:82)(cid:79)(cid:71)(cid:82)(cid:65)(cid:77)(cid:0)(cid:85)(cid:83)(cid:73)(cid:78)(cid:71)(cid:0)(cid:76)(cid:79)(cid:79)(cid:80)(cid:83)(cid:12)(cid:0)(cid:67)(cid:72)(cid:79)(cid:73)(cid:67)(cid:69)(cid:83)(cid:12)(cid:0)(cid:68)(cid:69)(cid:67)(cid:73)(cid:83)(cid:73)(cid:79)(cid:78)(cid:83)(cid:0)(cid:65)(cid:78)(cid:68)(cid:0)(cid:77)(cid:79)(cid:82)(cid:69) (cid:115)(cid:0)(cid:40)(cid:79)(cid:87)(cid:0)(cid:84)(cid:79)(cid:0)(cid:87)(cid:79)(cid:82)(cid:75)(cid:0)(cid:87)(cid:73)(cid:84)(cid:72)(cid:0)(cid:65)(cid:82)(cid:82)(cid:65)(cid:89)(cid:83)(cid:12)(cid:0)(cid:86)(cid:69)(cid:67)(cid:84)(cid:79)(cid:82)(cid:83)(cid:12)(cid:0)(cid:65)(cid:78)(cid:68)(cid:0)(cid:83)(cid:84)(cid:82)(cid:73)(cid:78)(cid:71)(cid:83) (cid:115)(cid:0)(cid:40)(cid:79)(cid:87)(cid:0)(cid:84)(cid:79)(cid:0)(cid:85)(cid:83)(cid:69)(cid:0)(cid:82)(cid:65)(cid:87)(cid:0)(cid:80)(cid:79)(cid:73)(cid:78)(cid:84)(cid:69)(cid:82)(cid:83)(cid:0)(cid:65)(cid:78)(cid:68)(cid:0)(cid:83)(cid:77)(cid:65)(cid:82)(cid:84)(cid:0)(cid:80)(cid:79)(cid:73)(cid:78)(cid:84)(cid:69)(cid:82)(cid:83) (cid:115)(cid:0)(cid:0)(cid:40)(cid:79)(cid:87)(cid:0)(cid:84)(cid:79)(cid:0)(cid:80)(cid:82)(cid:79)(cid:71)(cid:82)(cid:65)(cid:77)(cid:0)(cid:87)(cid:73)(cid:84)(cid:72)(cid:0)(cid:70)(cid:85)(cid:78)(cid:67)(cid:84)(cid:73)(cid:79)(cid:78)(cid:83)(cid:0)(cid:65)(cid:78)(cid:68)(cid:0)(cid:68)(cid:69)(cid:65)(cid:76)(cid:0)(cid:87)(cid:73)(cid:84)(cid:72)(cid:0)(cid:80)(cid:82)(cid:79)(cid:71)(cid:82)(cid:65)(cid:77)(cid:0)(cid:70)(cid:73)(cid:76)(cid:69)(cid:83)(cid:0)(cid:65)(cid:78)(cid:68)(cid:0) pre-processing directives (cid:115)(cid:0)(cid:40)(cid:79)(cid:87)(cid:0)(cid:84)(cid:79)(cid:0)(cid:68)(cid:69)(cid:70)(cid:73)(cid:78)(cid:69)(cid:0)(cid:89)(cid:79)(cid:85)(cid:82)(cid:0)(cid:79)(cid:87)(cid:78)(cid:0)(cid:68)(cid:65)(cid:84)(cid:65)(cid:0)(cid:84)(cid:89)(cid:80)(cid:69)(cid:83)(cid:0)(cid:85)(cid:83)(cid:73)(cid:78)(cid:71)(cid:0)(cid:67)(cid:76)(cid:65)(cid:83)(cid:83)(cid:69)(cid:83)(cid:0)(cid:65)(cid:78)(cid:68)(cid:0)(cid:67)(cid:76)(cid:65)(cid:83)(cid:83)(cid:0)(cid:79)(cid:80)(cid:69)(cid:82)(cid:65)(cid:84)(cid:73)(cid:79)(cid:78)(cid:83) (cid:115)(cid:0)(cid:40)(cid:79)(cid:87)(cid:0)(cid:84)(cid:79)(cid:0)(cid:83)(cid:73)(cid:71)(cid:78)(cid:65)(cid:76)(cid:0)(cid:65)(cid:78)(cid:68)(cid:0)(cid:72)(cid:65)(cid:78)(cid:68)(cid:76)(cid:69)(cid:0)(cid:69)(cid:82)(cid:82)(cid:79)(cid:82)(cid:83)(cid:0)(cid:85)(cid:83)(cid:73)(cid:78)(cid:71)(cid:0)(cid:69)(cid:88)(cid:67)(cid:69)(cid:80)(cid:84)(cid:73)(cid:79)(cid:78)(cid:83) (cid:115)(cid:0)(cid:40)(cid:79)(cid:87)(cid:0)(cid:84)(cid:79)(cid:0)(cid:68)(cid:69)(cid:70)(cid:73)(cid:78)(cid:69)(cid:0)(cid:65)(cid:78)(cid:68)(cid:0)(cid:85)(cid:83)(cid:69)(cid:0)(cid:70)(cid:85)(cid:78)(cid:67)(cid:84)(cid:73)(cid:79)(cid:78)(cid:0)(cid:84)(cid:69)(cid:77)(cid:80)(cid:76)(cid:65)(cid:84)(cid:69)(cid:83)(cid:0)(cid:65)(cid:78)(cid:68)(cid:0)(cid:67)(cid:76)(cid:65)(cid:83)(cid:83)(cid:0)(cid:84)(cid:69)(cid:77)(cid:80)(cid:76)(cid:65)(cid:84)(cid:69)(cid:83) (cid:115)(cid:0)(cid:40)(cid:79)(cid:87)(cid:0)(cid:84)(cid:79)(cid:0)(cid:68)(cid:79)(cid:0)(cid:70)(cid:73)(cid:76)(cid:69)(cid:0)(cid:73)(cid:78)(cid:80)(cid:85)(cid:84)(cid:0)(cid:65)(cid:78)(cid:68)(cid:0)(cid:79)(cid:85)(cid:84)(cid:80)(cid:85)(cid:84)(cid:0)(cid:87)(cid:73)(cid:84)(cid:72)(cid:0)(cid:35)(cid:11)(cid:11) Shelve in ISBN 978-1-4842-0008-7 Programming Languages/C++ 55999 User level: Beginning–Advanced SOURCE CODE ONLINE 9781484200087 www.apress.com 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 (cid:78) Chapter 1: Basic Ideas ......................................................................................................1 (cid:78) Chapter 2: Introducing Fundamental Types of Data .......................................................23 (cid:78) Chapter 3: Working with Fundamental Data Types .........................................................55 (cid:78) Chapter 4: Making Decisions ..........................................................................................79 (cid:78) Chapter 5: Arrays and Loops .........................................................................................105 (cid:78) Chapter 6: Pointers and References ..............................................................................151 (cid:78) Chapter 7: Working with Strings ...................................................................................185 (cid:78) Chapter 8: Defining Functions .......................................................................................213 (cid:78) Chapter 9: Lambda Expressions ....................................................................................271 (cid:78) Chapter 10: Program Files and Preprocessing Directives .............................................287 (cid:78) Chapter 11: Defining Your Own Data Types ...................................................................315 (cid:78) Chapter 12: Operator Overloading .................................................................................365 (cid:78) Chapter 13: Inheritance ................................................................................................399 (cid:78) Chapter 14: Polymorphism ............................................................................................429 v (cid:78) CONTENTS AT A GLANCE (cid:78) Chapter 15: Runtime Errors and Exceptions .................................................................463 (cid:78) Chapter 16: Class Templates .........................................................................................495 (cid:78) 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 (cid:78) 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: (cid:117)(cid:0) What is meant by Modern C++ (cid:117)(cid:0) The elements of a C++ program (cid:117)(cid:0) How to document your program code (cid:117)(cid:0) How your C++ code becomes an executable program (cid:117)(cid:0) How object-oriented programming differs from procedural programming (cid:117)(cid:0) What binary, hexadecimal, and octal number systems are (cid:117)(cid:0) 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 (cid:78) 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 <iostream> 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 << "The answer to life, the universe, and everything is " All the code in a << answer function is enclosed << std::endl; between braces. return 0; } This statement ends the function main. This statement is spread over three lines. Figure 1-1. A complete C++ program Comments and Whitespace The first two lines in Figure 1-1 are comments. You add comments that document your program code to make it easier for someone else to understand how it works. The compiler ignores everything that follows two successive forward slashes on a line so this kind of comment can follow code on a line. The first line is a comment that indicates the name of the file containing this code. This file is in the code download for the book. I’ll identify the file for each working example in the same way. The file extension, .cpp, indicates that this is a C++ source file. Other extensions such as .cc are also used to identify a C++ source file. All the executable code for a program will be in one or more source files. 2 CHAPTER 1 (cid:78) BASIC IDEAS There’s another form of comment that you can use when you need to spread a comment over several lines. For example: /* This comment is over two lines. */ Everything between /* and */ will be ignored by the compiler. You can embellish this sort of comment to make it stand out. For example: /************************ * This comment is * * over two lines. * ************************/ Whitespace is any sequence of spaces, tabs, newlines, form feed characters, and comments. Whitespace is generally ignored by the compiler, except when it is necessary for syntactic reasons to distinguish one element from another. Preprocessing Directives and Header Files The third line in Figure 1-1 is a preprocessing directive. Preprocessing directives cause the source code to be modified in some way before it is compiled to executable form. This preprocessing directive adds the contents of the standard library header file with the name iostream to this source file, Ex1_01.cpp. The header file contents are inserted in place of the #include directive. Header files, which are sometimes referred to just as headers, contain definitions to be used in a source file. iostream contains definitions that are needed to perform input from the keyboard and text output to the screen using Standard Library routines. In particular, it defines std::cout and std::endl among many other things. You’ll be including the contents of one or more standard library header files into every program and you’ll also be creating and using your own header files that contain definitions that you construct later in the book. If the preprocessing directive to include the iostream header was omitted from Ex1_01.cpp, the source file wouldn’t compile because the compiler would not know what std::cout or std::endl are. The contents of header files are included into a source file before it is compiled. (cid:78) Tip Note that there are no spaces between the angle brackets and the standard header file name. With some compilers, spaces are significant between the angle brackets, < and >; if you insert spaces here, the program may not compile. Functions Every C++ program consists of at least one and usually many more functions. A function is a named block of code that carries out a well-defined operation such as “read the input data” or “calculate the average value” or “output the results”. You execute or call a function in a program using its name. All the executable code in a program appears within functions. There must be one function with the name main, and execution always starts automatically with this function. The main() function usually calls other functions, which in turn can call other functions, and so on. Functions provide several important advantages: (cid:117)(cid:0) A program that is broken down into discrete functions is easier to develop and test. (cid:117)(cid:0) You can reuse a function in several different places in a program, which makes the program smaller than if you coded the operation in each place that it is needed. 3 CHAPTER 1 (cid:78) BASIC IDEAS (cid:117)(cid:0) You can often reuse a function in many different programs, thus saving time and effort. (cid:117)(cid:0) Large programs are typically developed by a team of programmers. Each team member is responsible for programming a set of functions that are a well-defined subset of the whole program. Without a functional structure, this would be impractical. The program in Figure 1-1 consists of just the function main(). The first line of the function is: int main() This is called the function header, which identifies the function. Here, int is a type name that defines the type of value that the main() function returns when it finishes execution - an integer. In general, the parentheses following a name in a function definition enclose the specification for information to be passed to the function when you call it. There’s nothing between the parentheses in this instance but there could be. You’ll learn how you specify the type of information to be passed to a function when it is executed in Chapter 5. I’ll always put parentheses after a function name in the text to distinguish it from other things that are code. The executable code for a function is always enclosed between braces and the opening brace follows the function header. Statements A statement is a basic unit in a C++ program. A statement always ends with a semicolon and it’s the semicolon that marks the end of a statement, not the end of the line. A statement defines something, such as a computation, or an action that is to be performed. Everything a program does is specified by statements. Statements are executed in sequence until there is a statement that causes the sequence to be altered. You’ll learn about statements that can change the execution sequence in Chapter 4. There are three statements in main() in Figure 1-1. The first defines a variable, which is a named bit of memory for storing data of some kind. In this case the variable has the name answer and can store integer values: int answer {42}; // Defines answer with the value 42 The type, int, appears first, preceding the name. This specifies the kind of data that can be stored - integers. Note the space between int and answer. One or more whitespace characters is essential here to separate the type name from the variable name; without the space the compiler would see the name intanswer, which it would not understand. An initial value for answer appears between the braces following the variable name so it starts out storing 42. There’s a space between answer and {42} but it’s not essential. A brace cannot be part of a name so the compiler can distinguish the name from the initial value specification in any event. However, you should use whitespace in a consistent fashion to make your code more readable. There’s a somewhat superfluous comment at the end of the first statement explaining what I just described but it does demonstrate that you can add a comments to a statement. The whitespace preceding the // is also not mandatory but it is desirable. You can enclose several statements between a pair of curly braces, { }, in which case they’re referred to as a statement block. The body of a function is an example of a block, as you saw in Figure 1-1 where the statements in main() function appear between curly braces. A statement block is also referred to as a compound statement because in most circumstances it can be considered as a single statement, as you’ll see when we look at decision-making capabilities in Chapter 4. Wherever you can put a single statement, you can equally well put a block of statements between braces. As a consequence, blocks can be placed inside other blocks—this concept is called nesting. Blocks can be nested, one within another, to any depth. 4

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.