35,99 €
Discover the impressive capabilities of C++ and learn the skills you need to implement it in real life
C++ is a general-purpose programming language built with a bias towards embedded programming and systems programming. Over the years, C++ has evolved and is used to develop software for many different sectors. Given its versatility and robustness, C++is a wonderful language to start your coding journey with. This book covers exciting projects built in C++ that show how to implement the language in different scenarios. While developing these projects, you will not only learn the language constructs but also how you can use C++ to meet your software requirements.
The book starts with a brief introduction to C++ language constructs where you will learn essential concepts that are required to understand the projects covered in the book. The first module will build a library management system that will teach you how to perform efficient file handling and use pointers in your software. To give you a taste of GUI programming, the next module will build graphical applications using Qt 5. You will then be introduced to game design in C++ and build two interesting games. The final module will teach you how C++ can be used to create a Domain Specific Language.
After reading this book, you will have mastered core programming concepts in C++, and how to implement them effectively.
This book is for developers who would like to develop software in C++. Basic programming experience would be an added advantage.
Stefan Björnander is the author of the books Microsoft Windows C++ and C++ Windows Programming. He holds a Master of Engineering and a Licentiate in Computer Science. He has worked as a software developer and as a teacher in computer science and mathematics for many years.Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 441
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Merint MathewAcquisition Editor: Chaitanya NairContent Development Editor: Lawrence VeigasTechnical Editor: Adhithya HaridasCopy Editor: Safis EditingProject Coordinator: Prajakta NaikProofreader: Safis EditingIndexer: Aishwarya GangawaneGraphics: Jisha ChirayilProduction Coordinator: Deepika Naik
First published: February 2018
Production reference: 1220218
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78839-181-8
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Stefan Björnander is the author of the books Microsoft Windows C++ and C++ Windows Programming. He holds a Master of Engineering and a Licentiate in Computer Science. He has worked as a software developer and as a teacher in computer science and mathematics for many years.
Mark Elston is a software architect for an automated test equipment company working primarily in the IC and mobile device test world. However, his 30 years of experience includes developing aircraft and missile simulations for the Air Force and Navy, hardware control systems for NASA, and tester operating systems for commercial products. He has also developed several Android applications for fun. His latest passion is delving into the world of functional programming and design.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
C++17 By Example
Dedication
Packt Upsell
Why subscribe?
PacktPub.com
Contributors
About the author
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
Getting Started with C++
Rolling the dice
Understanding classes – the Car class
Extending the Car class
A class hierarchy – the Person, Student, and Employee classes
A simple data type – the stack
A more advanced data type – the queue
Summary
Data Structures and Algorithms
The List class
The Cell class
The Iterator class
The List class
Adding a list to an existing list
Erasing a value from the list
The Set class
Union, intersection, and difference operations
Basic searching and sorting
The select sort algorithm
The insert sort algorithm
The bubble sort algorithm
The extended List class
The ReverseIterator class
The extended Set class
Union, intersection, and difference
Advanced searching and sorting
The merge sort algorithm
The quick sort algorithm
Summary
Building a Library Management System
The Book class
Writing the book
Reading the book
Borrowing and reserving the book
Displaying the book
The Customer class
Reading the customer from a file
Writing the customer to a file
Borrowing and reserving a book
Displaying the customer
The Library class
Looking up books and customers
Adding a book
Deleting a book
Listing the books
Adding a customer
Deleting a customer
Listing the customers
Borrowing a book
Reserving a book
Returning a Book
Saving the library information to a file
Loading the library information from a file
The main function
Summary
Library Management System with Pointers
The Book class
Reading and writing the book
Borrowing and reserving the book
Displaying the book
The Customer class
Reading and writing the customer
Borrowing and reserving a book
Displaying the customer
The Library class
Looking up books and customers
Adding a book
Deleting a book
Listing the books
Adding a customer
Deleting a customer
Listing the customers
Borrowing a book
Reserving a book
Returning a book
Looking up books and customers
Marshmallowing
Saving the library information to a file
Writing the book objects
Writing the customer objects
Writing the borrower index
Writing the reservation indexes
Writing the loan book indexes
Writing the reservation book indexes
Loading the library information from a file
Reading the book objects
Reading the customer objects
Reading the borrower index
Reading the reservation indexes
Reading the loan book indexes
Reading the reservation book indexes
Deallocating memory
The main function
Summary
Qt Graphical Applications
Creating the clock application
Setting up the environment
The Clock class
The main function
Setting up reusable classes for windows and widgets
Adding a listener
The base window class
The base widget class
Building the drawing program
The Figure base class
The Line sub class
The Rectangle sub class
The Ellipse sub class
Drawing the window
Drawing the widget
The main function
Building an editor
The Caret class
Drawing the editor window
Drawing the editor widget
The main function
Summary
Enhancing the Qt Graphical Applications
Improving the clock
The Clock class
The main function
Improving the drawing program
The Figure class
The Line class
The Rectangle class
The Ellipse class
The DrawingWindow class
The DrawingWidget class
The main function
Improving the editor
The EditorWindow class
The EditorWidget class
The main function
Summary
The Games
Othello
The game widget
The OthelloWindow class
The OthelloWidget class
The main function
Noughts and crosses
The NaCWindow class
The NaCWidget class
The main function
Summary
The Computer Plays
Othello
The OthelloWindow class
The OthelloWidget Class
The main function
Noughts and Crosses
The NaCWindow class
The NaCWidget class
The main function
Summary
Domain-Specific Language
Introducing the source language – a simple example
The grammar of the source language
The target language
The colors
Error handling
The value
The scanner
Building the parser
Parsing the instructions of the language
Parsing the expressions of the language
Type checking the expression
Evaluating the values of the expressions
The viewer
The main function
Summary
Advanced Domain-Specific Language
Improving the source language – an example
Improving the grammar
The Token and the Scanner
The parser
The evaluator
The main function
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
C++ is a general-purpose programming language built with a bias towards embedded programming and systems programming. Over the years, C++ has evolved and is used to develop software for many different sectors. Given its versatility and robustness, C++ is a wonderful language to start your coding journey with. This book covers exciting projects built in C++ that show how to implement the language in different scenarios. While developing these projects, you will not only learn the language constructs but also how you can use C++ to meet your software requirements.
In this book, you will study a set of applications written in C++, ranging from abstract datatypes to library management systems, graphical applications, games, and a Domain-Specific Language (DSL).
This book is for developers who would like to develop software in C++. Basic programming experience would be an added advantage.
Chapter 1, Getting Started with C++, introduces you to Object-Oriented Programming (OOP) in C++. We start by looking into a simple program that rolls a dice. We write the code, compile, link, and execute the program. We then continue by constructing a simple object-oriented hierarchy, with pointers and dynamic binding. Finally, we create two simple abstract data types: stack and queue. The stack is a set of values ordered in a bottom-to-top manner, where only the top-most value is accessible, while the queue is a traditional queue where we inspect values at the front and add values at the rear.
Chapter 2, Data Structures and Algorithms, builds on what was learned in the previous chapter, especially the list and set abstract datatypes. We also introduce templates and operator overloading, and we look into linear and binary search algorithms and the insert, select, bubble, merge, and quicksort algorithms.
Chapter 3, Building a Library Management System, will help you develop a real-world system: a library management system that is made up of books and customers. The books keep track of the customers that have borrowed and reserved them, and the customers keep track of the books they have borrowed and reserved.
Chapter 4, Library Management System with Pointers, further develops the library management system. In the previous chapter, each book and customer were identified by integer numbers. In this chapter, however, we work with pointers. Each book holds pointers to the customers that have borrowed or reserved it, and each customer holds pointers to the books they have borrowed or reserved.
Chapter 5, Qt Graphical Applications, dives into three graphical applications that we develop with the Qt graphical library: an analog clock with hour, minute, and second hands, a drawing program that draws lines, rectangles, and ellipses in different colors, and an editor where the user can input and edit text. We will learn how to handle windows and widgets as well as menus and toolbars in the Qt Library. We will also learn how to draw figures and write text, and how to catch mouse and keyboard input.
Chapter 6, Enhancing the Qt Graphical Applications, further develops the three graphical applications: the analog clock, the drawing program, and the editor. We add digits to the clock dial, we add the possibility to move, modify, and cut-and-paste figures in the drawing program, and we add the possibility to change font and text alignment in the editor.
Chapter 7, The Games, introduces you to basic game development. In this chapter, we develop the games Othello, and Noughts and Crosses with the Qt library. In Othello, two players take turn adding marks, colored black and white, to the game grid in order to enclose the opponent's marks. In Noughts and Crosses, two players take turns adding noughts and crosses to a game grid in order to place five marks in a row.
Chapter 8, The Computer Plays, empowers the computer to play against a human player. In Othello, the computer tries to add marks that enclose as many as possible of the opponent’s marks. In Nought and Crosses, the computer tries to add marks to obtain five marks in a row, and to prevent the opponent to get five marks in a row.
Chapter 9, Domain–Specific Language, teaches you to develop a Domain-Specific Language (DSL), which is a language intended for a specific domain. More specifically, we develop a language for writing graphical objects in a Qt widget. We start by formally defining our language with a grammar. We then write a scanner that recognizes meaningful sequences of characters, a parser that checks that the source code complies with the grammar, and a viewer that displays the graphical objects.
Chapter 10, Advanced Domain–Specific Language, improves on our Domain-Specific Language in several ways: we add selection and iteration that alter the flow of the program, we add variables that can be assigned to values during the program execution, and we add functions with parameters and a return value.
This book is intended for every reader, from the beginner to the more proficient C++ programmer. However, some previous experience with C++ is useful.
The examples of this book are developed in Visual Studio and Qt Creator.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/CPP17-By-Example. We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/CPP17ByExample_ColorImages.pdf.
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text. For example; "Let's continue with a class hierarchy, where Person is the base class with Student and Employee as its sub classes:"
A block of code is set as follows:
class Person { public: Person(string name); virtual void print(); private: string m_name; };
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
class Person { public:
Person(string name);
virtual void print(); private: string m_name; };
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "In the first dialog we just press the Next button:"
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
This chapter provides an introduction to Object-Oriented Programming (OOP) in C++. We start by looking into a simple program that rolls a dice. We write the code and compile, link, and execute the program.
Then we continue by constructing a simple object-oriented hierarchy, involving the Personbase class and its two subclasses, Student and Employee. We also look into pointers and dynamic binding.
Finally, we create two simple data types—stack and queue. A stack is constituted of a set of values ordered in a bottom-to-top manner, where we are interested in the top value only. A queue is a traditional queue of values, where we add values at the rear and inspect values at the front.
In this chapter, we will cover the following topics:
We start by implementing a simple game: rolling the dice. Its main purpose is to provide an introduction to the environment and teach you how to set up the project, and how to compile, link, and execute the program.
Then we start looking at object-oriented programming by writing a class hierarchy with
Person
as the base class and
Student
and
Employee
as subclasses. This provides an introduction to inheritance, encapsulation, and dynamic binding.
Finally, we write classes for the abstract data types stack and queue. A stack is a structure where we both add and remove values at the top, while a queue is more like a traditional queue where we add values at the rear and remove them from the front.
