程序代写 CE221 Part 1

Programming in C++ Part 1 Introduction
03/10/2019 CE221 Part 1

Module Schedule

Copyright By PowCoder代写 加微信 powcoder

There are two lectures (Monday 14.00-14.50 and Friday13.00- 13.50) each week in the autumn term, and a 2-hour lab at 9.00 on Wednesdays. (Note that the labs start in week 3 – there are none in week 2).
There will also be two revision lectures in the summer term.
03/10/2019 CE221 Part 1

Assessment
One two-hour examination in May/June (60% of the module credit)
Two programming assignments to be submitted by noon on Monday of week 8 and Wednesday of week 16 (20% each)
(Note that this module has no week 6 test.)
03/10/2019 CE221 Part 1

Recommended Reading
The main recommended text for this module is
Thinking in C++, B. Eckel, Volume 1, 2nd edition ( , 2000)
available for free download at
http://www.agitate.org.uk/eckel
Alternative books include
C++: How to Program, P.J. Deitel and H.M. Deitel, 10th edition (Pearson, 2016)
C++ for Java Programmers, T. Budd ( , 1999), and the definitive reference to the original version of C++
The C++ Programming Language, B. Stroustrup, 3rd edition ( , 2000) .
03/10/2019 CE221 Part 1

Motivation for Learning C++
C++ is more powerful and efficient than other high-level programming languages (although more complicated). C and C++ are the most widely used programming languages for robotics and games, and for writing compilers and operating systems and drivers of hardware devices.
Consequently a knowledge of C++ is a big advantage in the jobs market.
03/10/2019 CE221 Part 1

Learning Outcomes
After completing this module, students will be expected to be able to
 explain the basic concepts and features of C++.
 describe the underlying memory model and explain the role of the
execution stack and the heap.
 write object-oriented programs that incorporate basic C++ features such as pointers, references, inheritance, function overriding, operator overloading, exceptions, etc.
 make effective use of the C++ Standard Template Library.
03/10/2019 CE221 Part 1

Lecture Outline
The lectures for this module are divided into three main parts:
 Basics: fundamental types and variables, memory management, references, pointers, arrays, control structures, functions, classes and objects, operator overloading, an Array class, the string class, file processing, comparison of C++ and Java.
 Libraries: templates (function templates and class templates), containers, iterators, algorithms, the Standard Template Library (STL).
 Advanced topics: inheritance, polymorphism, exception handling.
03/10/2019 CE221 Part 1

C++ Development Environments
Development of a C++ program involves six phases: edit, pre-process, compile, link, load, execute.
Disk Memory CPU
Popular IDEs include ++, Visual C++, MFC. However, in the labs we shall be using TextPad.
03/10/2019 CE221 Part 1

“Hello World” in Java, C and C++ 1 // Java
public class HelloWorld
{ public static void main(String args[])
{ System.out.print(“\nHello, World!\n”);
#include
/* could use int main() */
main() /* default return type is int */ { printf(“\nHello, World!\n”);
03/10/2019 CE221 Part 1

“Hello World” in Java, C and C++ 2 // C++
#include
// using namespace std;
// could use int main(int argc, char* argv[]) or // int main(int argc, char* argv[], char **env) main() // default return type is int
{ // cout << "\nHello, World!\n"; std::cout << "\nHello, World!\n"; // return 0; } 03/10/2019 CE221 Part 1 Some Notes on the C++ Version 1 The main “method” in a C++ program is not written inside a class; the term function is used instead of method. The main function may take arguments to access command- line arguments, but these are optional; its return type is int. However, when a function is declared without a return type it is by default given the type int so we can simply write It is not regarded as an error if a function fails to return a result; in this case the result is unspecified. Since no attempt will be made to access the result returned by main we may hence omit the return statement. 03/10/2019 CE221 Part 1 Some Notes on the C++ Version 2 Screen output is sent to a stream called cout, defined in a namespace called std. We have to inform the compiler of the namespace: we can do this explicitly using std::cout, or we can use a using statement (as seen in the commented-out line) to indicate that we wish to use the namespace std to resolve any otherwise undeclared identifiers and then simply use cout. The << operator is used to send values to be output to a stream; we may chain these, e.g. cout << '\n' << "Hello, World!" << '\n'; 03/10/2019 CE221 Part 1 Some Notes on the C++ Version 3 In Java information about external classes is stored in their .class files and we import these; however in C++ (and C) this information is stored in the form of declarations in a text file called a header and to make these available to the compiler we must include the contents of appropriate header files within the source code using #include. The header file(s) will be copied onto a temporary copy of the source file before the main compilation process begins; the compiler then uses this temporary file as the source file. (The temporary file is annotated with information about the line numbers from the original files so that error messages can correctly report line numbers.) 03/10/2019 CE221 Part 1 “Hello World” Using a Class 1 We now present a version of a “Hello World” program in which the output is produced in a class and the main function makes a call to a function in this class. #include
using namespace std;
// HelloWorld class definition // (a user-defined type)
class HelloWorld
void displayMessage()
{ cout << endl << "Hello, World!" << endl; } }; // semicolon to terminate class definition 03/10/2019 CE221 Part 1 “Hello World” Using a Class 2 Here is the rest of the program. int main() { HelloWorld myHelloWorld; myHelloWorld.displayMessage(); return 0; } It is conventional to start class names with upper-case letters and variables and function names with lower-case letters. We have used endl instead of '\n'; this makes the program easier to read. The term member function is used in C++ to refer to a method of a class. 03/10/2019 CE221 Part 1 “Hello World” Using a Class 3 Note that as in Java, a default no-argument constructor is generated if we do not provide any constructor for a class. Furthermore, unlike in Java, if we declare an object variable without initialisation its no-argument constructor is called implicitly. Hence we simply use HelloWorld myHelloWorld; Note that the new keyword in C++ does something slightly different to that in Java so an attempt to use HelloWorld myHelloWorld = new HelloWorld(); would result in a compilation error. 03/10/2019 CE221 Part 1 Using Separate Files 1 Most classes written in C++ will be expected to be reused so it is common practice to write each class in a separate file, along with a header file that can be included in each file that uses the class. Although this is, of course, unnecessary for our simple program, we shall perform the splitting into separate files in order to demonstrate how to do this. A class definition containing all of its variables and the declarations of all of its functions without their bodies is placed in a header file with a .h extension; the complete function definitions are then provided in a source file for the class with a .cpp extension. 03/10/2019 CE221 Part 1 Using Separate Files 2 The header file for our HelloWorld class will be // HelloWorld.h class HelloWorld { public: void displayMessage(); The file containing the main function will be // HelloMain.cpp #include "HelloWorld.h" int main() { HelloWorld myHelloWorld; myHelloWorld.displayMessage(); return 0; } 03/10/2019 CE221 Part 1 Using Separate Files 3 Note that when including files that are in the user's folders we specify the filename(s), including the .h extension, inside quotes in the #include directive(s). The angled brackets as used for #include are used for header files that are found in the C++ system folders.
It would be possible simply to write the complete definition of the HelloWorld class in a HelloWorld.cpp file; however the compiler will then not perform any checks to see if the definition is consistent with that in the header file. When developing classes that will be modified as we proceed it is essential that such checks are performed. Hence the header file should be included in the class file.
03/10/2019 CE221 Part 1

Using Separate Files 4
Assuming the HelloWorld.h file is to be included in the HelloWorld.cpp file its contents will be copied into the the latter file at compilation time. Hence this file will contain a definition for the HelloWorld class and we cannot write another definition in the file.
Consequently we have to write the function body outside of the class definition and indicate that it is a member of the class by prefixing its name with the class name using
void HelloWorld::displayMessage()
The source file for the class can be seen on the next slide. 03/10/2019 CE221 Part 1

Using Separate Files 5
#include
#include “HelloWorld.h”
using namespace std;
void HelloWorld::displayMessage()
{ cout << endl << "Hello, World!" << endl; } 03/10/2019 CE221 Part 1 Avoiding Duplicate Header Inclusion 1 Many header files need to include other header files; for example any header file with classes which have members of type string would need to contain the line #include
If a user’s program included more than one such file the nested includes would result in the header file for the string class being included more than once in his program. We might expect that this would lead to compilation errors due to duplicate class definitions. This however is not the case; the header file for the string class has been written in such a way that if the class declaration has already been included it will not be included again.
03/10/2019 CE221 Part 1

Avoiding Duplicate Header Inclusion 2
The contents of header files are inserted into the temporary copy of the source file by the preprocessor, the first step of the compilation process.
To prevent class declarations being duplicated header files should use preprocessor directives to provide conditional inclusion:
// myClass.h
#ifndef _MYCLASS_H_
#define _MYCLASS_H_
// use names like _MYCLASS_H_ to avoid
// potential clashes with program variable // names
// body of header file comes here
03/10/2019 CE221 Part 1

Avoiding Duplicate Header Inclusion 3
In the example on the previous slide when a first attempt is made to include the file the preprocessor will find that the preprocessor variable _MYCLASS_H_ has not been defined so the contents of the file will be included. The next line of the file is a preprocessor directive to define this variable (giving it an empty string as a value, since there is nothing on the line after the name of the variable). The body of the header file is then included in the source program.
If a second attempt is then made to include the file the preprocessor will find that the variable has been defined so all lines between the #ifndef directive and its matching #endif will be ignored.
03/10/2019 CE221 Part 1

Avoiding Duplicate Header Inclusion 4
Here is a version of HelloWorld.h that uses preprocessor directives to avoid any possibility of duplicate inclusion.
// HelloWorld.h
#ifndef _HELLOWORLD_H_ #define _HELLOWORLD_H_ class HelloWorld
void displayMessage();
03/10/2019 CE221 Part 1

A Typical C++ Program Framework
// Class1.h
#ifndef _CLASS1_H_
#define _CLASS1_H_
// include headers
class Class1 { public:
Class1(/* args* /);
// other members
// members
// Class1.cpp
// include headers
Class1::Class1(/* args */) { // constructor
// implementation
// implementation of other
// members
// main.cpp
// include headers
main(int argc, char *argv[]) { // create objects, use them }
(Add more classes: Class2, Class3, …)
03/10/2019 CE221 Part 1

Primitive Types 1
C++ has a large number of primitive types:
short int (or short) int
long int (or long)
long long int (or long long)
unsigned char
unsigned short int (or unsigned short) unsigned int (or unsigned)
unsigned long int (or unsigned long)
unsigned long long int (or unsigned long long)
float double long double
03/10/2019 CE221 Part 1

Primitive Types 2
The value of a data item of type bool is either true or false. Any numeric value may be used in a context where a boolean is required; non-zero values are interpreted as true and 0 as false.
The next 10 types listed on the previous slide are all regarded as integer types and it is possible to freely assign between them – overflow may of course occur.
The unsigned versions cannot hold negative values: an initialisation such as unsigned int i = -1; will result in the value of i being the integer that has the same value as the two’s complement representation of -1, i.e. the maximum value for the type int.
03/10/2019 CE221 Part 1

Primitive Types 3
The range of values that may be stored in a data item of each type is hardware-dependent. A char will almost invariably have 8 bits, a short will have at least 16 bits and a long will have at least 32 bits. The unsigned versions will always have the same number of bits as their signed counterparts.
In most modern implementations the short type uses 16 bits, both int and long use 32 bits and long long uses 64 bits.
The float type usually uses 32 bits, double 64 bits and long double 128 bits.
Since in some older implementations the int type has only 16 bits it is wise to use long for any variable or class member that is expected to sometimes take values larger than 32767.
03/10/2019 CE221 Part 1

Memory and Storage
The computer memory for a C++ program has four areas.
There is an area which stores the code and constants. This is pretty much invariant – the code shouldn’t change.
Data items are stored in three areas:
 a static area for items whose lifetime is the duration of the program.
 a stack area for local variables in functions, whose lifetime is the invocation of a function; this area is also used to pass arguments to functions and return results, and to store return addresses.
 a heap area for dynamic items, whose lifetime is controlled by the programmer
03/10/2019 CE221 Part 1

A variable in a programming language has three major attributes.
It has a type (e.g. int, bool, string, Student). Types may be primitive or classes.
It has lifetime (or extent). It is born, it is used, it dies.
It has scope (or visibility). When it is in existence, what other
things can see it?
It also has a name, a size (i.e. how much memory it occupies), and a value.
03/10/2019 CE221 Part 1

Storage Classes and Variable Lifetime 1
There are five storage classes:
automatic: for local variables only, existing only when the block in
which the variables are defined is active.
register: for local variables only, for fast access, rarely used nowadays.
mutable: for class members only, to make them always modifiable even in a const member function or as a member of a const object.
external: for identifier linkage of global variables and functions, lasting for the duration of the program.
static: for variables and class members that last for the duration of the program and can be initialised once only
There are five keywords that can (or could) be used to indicate that a variable should have one of these classes: auto, register, mutable, extern and static.
03/10/2019 CE221 Part 1

Storage Classes and Variable Lifetime 2
Since local variables are usually stored on the stack by default the use of auto keyword to a variable should be automatic is obsolete and since C++11 it is no longer used for this purpose but has a totally different meaning.
The register class is used to indicate that a frequently-accessed local variable should be stored in a register instead of memory in order to optimise performance; such optimisations are rarely necessary on modern machines.
A const member function cannot normally change the values of members of the object to which it is applied. There may be rare occasions when we wish to allow the value of a particular member to be changed in such a function (for example, during program development it may be desirable to add an access counter when analysing for possible optimisations), hence the
need for mutable variables.
03/10/2019 CE221 Part 1

Storage Classes and Variable Lifetime 3
A static data item exists for the duration of the program and can be initialised only once. Classes can have static members; in this case one copy is shared by all of the objects of that class.
If a local variable in a function is declared to be static it is initialised when the program starts running and retains its value between calls to that function.
A static variable must be initialised with a value when it is declared, e.g.
static int x = 77; // not static int x;
03/10/2019 CE221 Part 1

Storage Classes and Variable Lifetime 4
A global variable is one that is defined outside any class or function. If a program is split between several files it may be necessary to access the same global variable in more than one file. The variable can however be declared in only one of the files so in all of the others it must be declared as external.
For example, if one file contains the global declaration
int a = 5;
and we need to access a in another file we would need to include the declaration
extern int a;
in that file. This if often done by placing the line in a header file associated with the first file and included in the second file.
03/10/2019 CE221 Part 1

The scope of a variable specifies where in the program it can be accessed. A variable declared locally in a block of code can be accessed only between its declaration and the end of that block. If, within the block we make a call to a function, the variable cannot be accessed within the function.
A private member of a class can be accessed only within that class and its member functions and friend functions (we shall see what a friend function is later). The member functions may be defined outside the class body as seen in our example on slide 20. If our HelloWorld class had any private members they would have been accessible in the displayMessage function.
03/10/2019 CE221 Part 1

A local variable may have the same name as a variable that is already in scope; the following code fragment is valid.
int a = 0; // global
int myFunc()
{ char a = ‘x’;
Within the body of myFunc any occurrence of a will refer to the local variable. If we need to access the global variable we must use ::a.
03/10/2019 CE221 Part 1

Example and Exercise
#include
using namespace std;
int a = 1;
{ int b = 1;
What are the scope and lifetime of a,b,candd?
static int c = a; // initialised once only int d = a; // initialised at each call of f() cout << "a=" << a++ << " b=" << b++ << " c=" << c << " d=" << d << endl; int main() { while (a<4) What would be the outputs? 03/10/2019 CE221 Part 1 程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com