Vous êtes sur la page 1sur 47

y

Memory Memory stores data and programs. There are two kinds of memory - primary storage (including RAM and ROM) and secondary storage (usually a hard disk). Note: ROM is read-only memory that contains code needed to start the computer.

Bus The CPU, RAM memory, and the electronics controlling the hard disk and other devices are interconnected through a set of electrical lines called a bus.

Program instructions and data are stored on the hard disk, on a CD -ROM, or elsewhere on the network. When a program is started, it is brought into RAM memory, from where the CPU can read it. The CPU reads the program one instruction at a time. As directed by these instru ctions, the CPU reads data, modifies, it and writes it back to RAM memory or the hard disk. Register A register is the storage location in the CPU. Machine instructions (Machine codes) Machine instructions are encoded as numbers. On a processor from a different manufacturer, the encoding would be quite different.

Assembly Easier to read (by assigning short names to commands). Another computer program called assembler translates it into machine codes. The assembly instructions still differs from one processor to another.

higher-level programming language Translated by a special computer program called compiler into machine codes. Higher-level languages are independent of the underlying hard -ware. They are compiled to different code on different processors.

#include <iostream> A C++ standard library header file containing function prototypes for the C++ standard input and standard output functions. Allows program to output data to the screen or input data from the keyboard. eg. fix

#include<iomanip> A C++ standard library header file containing function prototypes for stream manipulators that format streams of data. eg. setprecision(), setw() #include<string> A C++ standard library header file containing definition of class string. Also enable the use of the function getline.

#include<cmath> A C++ standard library header file containing function prototypes for math library functions. eg. pow(x, y); sqrt(x); log(x); log10(x); ceil(x); floor(x); fabs(x);

#include <cstdlib> A C++ standard library header file containing function prototypes. eg. rand(), srand(seed), abs(x);

[Note: rand() yields a random integer between 0 and RAND_MAX. ] To yield a random number between a and b: int r = a + rand() % (b - a + 1); y using namespace std allow us to use cout, cin, endl directly instead of writing std cout, std cin, std endl.

Compile-time error (syntax error) Something is wrong according to the language rules. Source code will not compile. Run-time error (logic error) The program is syntactically correct but doesn t do what it is supposed to do. The compiler cannot find the error. Overflow error Computers can make overflow errors when you ask them to perform computations whose results falls outside their numeric range. Library Library is a collection of code that has been programmed and translated by someone else, ready for you to use in your program. The compilation process

Program statements are entered into a text editor. The compiler translates the C++ source code (that is, the statements that you wrote) into machine code. Note that the machine code contains only the translation of the code that you wrote. That is not enough to actually run the program. A special program called linker takes your machine code file and the necessary parts from the library (eg. iostream library) and builds an executable file. The executable file is usually ended with .exe Note: a library is a collection of code that has been programmed and translated by someone else, ready for you to use in your program. Also the machine code has an extension of .obj or .o. y Constants Constants must be initialized when declared. const type_name variable_name = initial_value; y Variable Defn variables names must start with a letter or underscore,, and the remaining characters must be letters, numbers, or underscores. p.35 Big C++ Number types The name for the floating-point number used is double. To write numbers in exponential notation in C++, use an En instead x10 n . For example, 5.0 x 10-3 becomes 5.0E-3. Putting a floating-point value into a int variable, the fractional part will be lost. (This is not necessarily the closest integer) Note that when dividing two integers, the result is always an integer, with the remainder discarded. eg. 7/4 = 1 Division works as expected, as long as at least one of the numbers involved is a floating-point number. Note that short (16 bit) and long (64 bits) are integer types. y Rounding to the closest integer

static_cast<int>(x + 0.5) [Note: here x is a floating number] y \n Note that this is a special character. eg. std cout Welcome to C++ \n ; Position the screen cursor to the beginning of the nex t line. y static_cast<int>(2.6); change it to an integer by truncating (or similarly round down).

String are enclosed in double-quotes. String is a sequence of characters. Strings are enclosed in quotation marks. This enables the compiler to consider them as plain text and not program instructions. eg. Hello Note: to include double quote in a string, use escape sequence. eg. \ Hello \ Unlike number variables, string variables are guaranteed to be initializ ed. They are initialised with the empty string. [Note: There is another data type char, used to denote i ndividual characters. individual characters are enclosed in single quotes.]

Name s.length() s.substr(i) s.substr(i, n) getline(f, s)

Purpose the length of s The substring of s from index i to the end of the string The substring of s of length n starting at index i Read string s from the input stream f

Lengths of strings The number of characters in a string is called th e length of the string. blank space and newline character are count as one character only. eg. str.length()

Concatenation The + operator concatenates two strings. However, one or both of the strings surrounding the + must be a string object. Output formatting To format output, include the line: #include <iomanip> Output can be formatted with functions from the iomanip library such as: setw(): Sets the field width of the next item only. left: Selects left alignment. right: Selects right alignment (default). fixed: Selects fixed format (6 digits after the decimal point) for floating point numbers. setprecison(): Sets the number of significant digits for general format; Sets the number of digits after the decimal point for fixed format. eg. cout fixed setprecision(2) [Note: setprecision and fixed manipulators need only to be used once. However, setw must be specified anew for every item.] Also see p.97 C++ How to program

ABOUT CIN By default, leading whitespace (carriage returns, tabs, spaces) is ignored (while consumed from the buffer) by cin. Keyboard input is buffered. When the user hits the En ter key, all input is placed into a buffer. eg. Suppose you enter 8 0 4 3 then Enter Buffer = 8 0 4 3 \n When entering multiple values in a line, all that matters is that the values are separated by white space: that is, blank spaces, tabs, or newlin es. That is, the values in the buffer are read one by one separated by a blank space, tab, newline or something unexpected. Note that cin does not consume the following white space, typically a newline \n. That is, the white space following the value read into cin is still in the buffer. But note that leading white spaces are ignored as said above. When cin encounters something unexpected, it will also set itself to a failed state , and all subsequent input statements will be ignored. The something unexpected will still be in the buffer. We can test the state of cin by the cin.fail() Note: whatever is remained in the buffer stays until being cleared If cin is in a fail state, then cin.fail() is true. how to use cin.clear() #include <iostream> using namespace std; int main(){ int x = 0; int y = 0; cin >> x; cin.clear(); string z; cin >> z;

cin >> y;

cout << " x is equal to " << x << " y is equal to " << y; return 0; } To clear the fail state of cin. We can use the cin.clear(). Method 1 cin.clear(); cin.ignore(1000, \n );

//Clear fail state so that cin can continue process inputs //Clear what is left in the buffer

Method 2 cin.clear(); //Clear fail state so that cin can continue process inputs string sentinel; getline(cin, sentinel); //read the remaining in the buffer into sentinel

Code #include <iostream> using namespace std; int main(){ int x = 0; string str = "default"; cin >> x; cin >> str; cout << "x is " << x << " str is " << str; return 0; } #include <iostream> using namespace std; int main(){ int x = 0; string str = "default"; cin >> x; cin.clear();

Command Prompt .75

Output x is 0 str is default

.75

x is 0 str is .75

cin >> str; cout << "x is " << x << " str is " << str; return 0; }

Reading input from a file In the command prompt window, type: a < input.txt Note that when reading input from a file, cin.fail() will be 1 when: (1) When cin encounters something unexpected. (2) When the end of file (eof ) is reached. Note that the end of file is reached when after reading something, nothing is behind it. It is important to know that a newline character or space is NOT nothing. Note that if the end of file is reached, cin.eof() will be equal to 1.

getline The getline command reads all keystrokes until the Enter key. eg. getline(cin, name) Reads all keystrokes until the Enter key and places it into the name variable. The getline function reads an entire line of input, consuming also the newline character at the end of the line. But only places characters before the newli ne character into the variable. It DOES NOT place the newline character into the variable. Note that since the newline character is consumed, it is no longer in the buffer. (Note: the newline character counts as one character only. See p.63 Big C++) In other words, the getline function reads characters until the newline character is encountered, places the characters in a string variable and discards newline character.

Enumerated Types eg. enum Weekday{MONDAY, TUESDAY, WEDNESDAY}; homework_due_date = WEDNESDAY; Note that: cout homework_due_date gives 2. Note: homework_due_dat = 1; is a compile time error.

Time Objects Time x = Time(); Time x = Time(23, 59, 59); Time x; //This invokes the default constructor of the class See p.70 Big C++ Time x(19, 0, 0); Time x() WRONG Purpose Constructs the current time Constructs the time with hours h, mintues m, and seconds s. Returns the seconds value of t Returns the minutes value of t Returns the hours value of t Changes t to move by n seconds Computes the number of seconds between t

Name Time() Time(h, m , s) t.get_seconds() t.get_minutes() t.get_hours() t.add_seconds(n) t.seconds_from(t2)

and t2. To use time class, include the header file that contains its declarations: #include ccc_time.h [Note: we use instead of < > because the file is not part of the standard C++ headers . Also, ccc_time.h should be in the same directory as the application file.] To compile the program, in MinGW, use g++ -o myapp time.cpp ccc_time.cpp Here, myapp is the name of the final executable file, time.app is the file that contains the main() and ccc_time.cpp is the file that contains the definition of Time class.

About vector C++ provides a standard template container called vector. To use vectors, include the line: #include <vector> Vector allows us to store a collection of data items of the same type. For example: vector<int> my_int; // my_int is a vector of integers vector<string> my_string; // my_string is a vector of strings To store data to a vector, use the member function push_back(): int iNum =123; my_int.push_back(iNum); // my_int holds 123 at index 0 my_int.push_back(456); // my_int holds 456 at index 1 string str= Hello! ; my_string.push_back(str); // my_string holds str at index 0;

Relational operators Relational operators (< <= > >= !=) can be used to compare strings. They are compared in dictionary order. But note that C++ is case sensitive and sorts characters by listing numbers first, then uppercase characters then lowercase characters. When comparing strings, corresponding characters are compared until

one of the strings ends or the first difference is encountered. If one of the string ends, the longer string is considered the later one. p.106 Big C++ Note: relational operators cannot be used to compare objects of arbitrary classes. For example, if s and t are two objects of the Time class, then the comparison s==t is an error. Also, you can only compare numbers with numbers and strings with strings. y If-else statements If (condition){ statement1; statement2; } else if (condition){ statement3; . } else { statemetn4; } An else always belongs to the closest if (when it is not clear which if it belongs to). For if-else statement with multiple alternatives, as soon as one of the tests succeeds, no further tests will be attempted. Note the expression inside if() need not be a logical condition. Any numerica val ue can be used inside a condition, with the convention that 0 denotes false and any non-0 value denotes true. p.107 Big C++ Moreover, C++ assignments are also expressions and have values. For example, the value of the expression a = 5 is 5. y The Switch Statement The switch statement consists of a series of case labels and an optional default case. The test cases must be constants, and they must be integers. The switch statement compares the value of the controlling expression with each case label. Without break statements, once a match occurs in the switch, the statements for that case and subsequent cases execute until a break statement or

the end of the switch is encountered. This is referred to as falling through to the statements in subsequent cases. switch(controlling expression) { case const1: statement1; break; case const2; statement2; break; default: statement; break; } y The Selection Operator test ? value1 : value2 The value of the expression is either value1 if the test passes or value2 if it fails. For example, we can compute the absolute value as y = x >= 0 ? x : -x; which is a shorthand for if (x >= 0) y = x; else y = -x;

Bool To store a condition that can be true or false, you use a variable of a special data type bool. That type has exactly two values, denoted false and true. The && and || operators are computed using lazy evaluation. As soon as the truth value is determined, no further conditions are evaluated. Note that && and || returns a true or false value. But true and false are automatically converted into 1 and 0 respectively in some situations: ie. cout true; //this gives 1

ie. if(-0.5 <= x <= 0.5). This is not a syntax error but a logical error. See p.117 An expression which yields a numerical value is automatically converted to true or false when operated on by && or ||. ie. if(x && y > 0); is a logical error but not a syntax error.

Zero is converted to false and any nonzero value is converted to true. See p.118 Big C++ y While statements while (condition){ statement; } y For Loop for (i = start; i <= end; i++){ statement; } // i is no longer defined here The control variable i can be used only in the body of the for statement, the control variable will be unknown outside the for statement. Note: if we run into a loop without the body, it is important that you really make sure that the semicolon is not forgotten. See p.129 Big C++ y Do Loop Sometimes you want to execute the body of a loop at least once and perform the loop test after the body is executed. The do loop serves that purposes. do{ statements; } while (condition); y Break statement break; The break statement breaks out of the enclosing loop, independent of the loop condition. p.135 Big C++ y Processing Inputs A value, which is not an actual input, but serves as a signal for termination of a loop, is called a sentinel.

rand() C++ has a random number generator, which produces numbers that appear to be completely random. Calling rand() yields a random integer between 0 and RAND_MAX (typically 32767 or 2147483647). Note rand() includes the bounds 0 and RAND_MAX. To use rand function, we must include the cstdlib header. rand() only produces pseudorandom numbers, to overcome the problem we can write: Time now; int seed = now.seconds_from(Time(0, 0, 0)); srand(seed); Simply place these instructions at the beginning of your program, before generating any random numbers. Then the random numbers will be different in every program run. To generate a random number between a and b (including the bounds themselves): int r = a + rand() % (b - a + 1);

Function Definition return_type function_name(type parameter1, type parameter2, { statements; return expression; }

, type parametern)

Note that the first line in the function definition is called the function header. Starting from { and ending at }, we have the function body. A function definition must contain a function header and the body of the function. Note that when the return statement is processed, the function exi ts immediately. The return statement need not be placed at the end. Also, there can be more than one return statement in the function. A function that returns a truth value is called a predicate function.

The variables in the function header are called parameters (or parameter variables, formal parameters). A function call supplies values or expressions for the function parameters. These values or expressions are called arguments (or parameter value, actual parameter). That is, when you call a function, its parameter variables are initialized with the corresponding expressions or values in the function call.

For example: /** Computes the maximum of two integers. @param x an integer @param y another integer @return the larger of the two inputs */ int max(int x, int y){ if (x > y) { return x; } else { return y; } } Note: A function should not have side effects, for example, disp laying characters on the screen, updating variables outside the function, terminating the program, etc. y Type Mismatch The compiler takes the function parameter and return types very seriously. It is an error to call a function with a value of an incompatible type. The compiler ONLY converts between integers and floating-point numbers, but it does not convert between numbers and strings or objects. For example, you cannot give a string to a numerical function, even if the string contains only digits. eg. string num = 1024 ; double x = sqrt(num); // Error Also, you cannot store a numerical return value in a string variab le: string root = sqrt(2); //Error

Function Declaration (or Prototype) A declaration (also called prototype) of a function lists the type of data returned by the function, the name of the function, the types of its parameters , but it contains no body. The parameter names are optional in function prototypes and each function prototype must end with a semicolon. [Note: The header of the function definition is similar in structure to a function prototype, except it must provide the parameters and not jus t their data types.]

return_type function_name(type , type, ); Eg. double abs(double x);

Note that function definition is different from function declaration. Declarations end in a semicolon, whereas definitions are followed by { } block. The purpose of function declaration is so that it can be called before it is defined. y Function Signatures The portion of a function prototype that includes the name of the function and the parameters is called the function signature or simply the signature. The function signature does not specify the function s return type. Function in the same scope must have unique signatures. The scope of a function is a region of a program in which the function is known and accessible. Procedures A procedure is a function that does not return a value. Reference Parameter type_name& parameter_name Eg. int& result

When we make e into a reference parameter, then e is not a new variable but a reference to an existing variable, and any change in e is actually a change in the variable to which e refers in that particular call. A reference parameter must be bound to a variable in the call, whereas a value parameter can be bound to any expression. Seep.179 Big C++ y Constant Reference Parameter const type_name& parameter_name Changing a constant reference parameter is an error. See p.181 Big C++ Variable Scope In a program, the part within which a variable is visible is known as the scope of the variable. The scope of a variable that is defined in a function extends from its definition to the end of the block in which it was defined. Variables that are defined inside functions are sometimes called local variables. In other words, variables declared insi de functions are known as local variables and can be used only from the line of their declaration in the function to the immediately following closing right brace } of the function definition. A local variable must be declared before it can be used in a function. A local variable cannot be access ed outside the function in which it is declared. When a function terminates, the values of its local variables are lost. (One exception is the static local variable). Variables that are defined outside functions are called global variables. A global variable is visible to all functions that are defined after it. y Precedence See p.135 of Small C++ How to program Commenting Out a Section of Code Not all compilers allow nested comments. ie. /* /* */ */

The first */ encountered matches up with the first /*. The */ at the end will cause an error message. There is another way of masking out a block of code: by using so -called preprocessor derectives.

ie. #if 0 .. #endif Note: if you want to include the block temporarily, change #if 0 to #if 1.

assert() What should a function do when it is called with inappropriate inputs? A good practice is for the function to complain loudly during testing, by printing an error message that clearly indicates the problem with the parameter value. The assert macro was designed for this purpose. If the condition inside the assert macro is false, then the program aborts with an error message that shows the line number and file name. If the condition inside the macro is true when the macro is encountered, then nothing happens. When write a function we should: (i) Establish clear preconditions for all inputs. Write in the @param comment what values you are not willing to handle for each parameter. [Note: preconditions are documented restrictions on the function parameters.] (ii) Write assert statements that enforce the preconditions. (iii) Be sure to supply correct results for all inputs that fulfil the precondition.

Syntax: assert(expression); eg. assert(x >= 0); If the expression is true, do nothing. If it is false, terminate the program, displaying an error message with the file name, line number, and expression.

To use assert we must write: #include <cassert> y Class Defintion Syntax: class ClassName { public: constructor declarations member function declarations(prototypes) private:

}; //Must have semicolon after the closing brace }

Function prototypes (can be without data name, just the type will suffice) are declared within the class definition. Functions can be declared and defined within the class definition. However, most func tions can have very large definitions and make the class very unreadable. Therefore it is possible to define the function outside of the class definition using the scope resolution operator " ::". This scope resolution operator allows a programmer to define the functions somewhere else. This can allow the programmer to provide a header file .h defining the class and a .obj file built from the compiled .cpp file which contains the function definitions. Note that a header file may contain class definitions and function prototypes. Programs use #include pre-processor directives to include header files. Note: when not specified, all members of a class (including member functions, data fields) are private. See Quiz 4 Q10 y Constructor Constructor is used to initialize an object of the class when the object is created. A constructor is a special member function that must be defined with the same name as the class, so that the compiler can distinguish it from the class s other member functions. An important dif ference between constructors and other functions is that constructors cannot return values, so they cannot speci fy a return type (not even void). Normally, constructors are declared public.

C++ requires a constructor call for each object that is created, which helps ensure that the object is initialized properly before it is used in a program - the constructor call occurs implicitly when the object is created. In any class that does not explicitly include a constructor, the compiler provides a default constructor - that is, a constructor with no parameters. If any constructor is provided, the compiler will NOT provide the default constructor. By the way, a default constructor is a constructor with no parameters. p.241 Big C++ [Note: For data members that are objects of other classes, the default constructor implicitly calls each data member s default constructor to ensure that the data member is initialized properly. In fact, this is why a string data member will be initialized to the empty string - the default constructor for class string sets the string value to the empty string.] In the code for the default constructor, you need to worry about initializing only numerical data fields. The data field for a string is automatically set to the empty string by the default constructor of the string class. In general, all data fields of class type are automatically constructed when an object is created, but the numeric fields must be set in the class constructors. It is common for a class to have multiple constructors. This allows you to define object in different ways. When two function share the same name but are distinguished by their parameter types, the function name is overloaded. When you construct an object, the compile r chooses the constructor that matches the parameter values that you supply. Note that the functions which are overloaded do not share the same function signature. y Mutator member function A mutator member function of a class changes the state of the object on which is operates. For example, if the class has a single mutator: read. After you call p.read(); the contents of p have changed. y Accessor member function An accessor member function does not modify the object. It q ueries the object for some information without changing it.

Accessor function should be tagged with const. The position of the const keyword occurs after the closing parenthesis of the parameter list, but before the semicolon that terminates the function declaration. ie. double get_x() const; See p.234 Big C++ Note: const should be attached to both function declaration (prototype) in class definition and the corresponding function definition. y The definitions of member functions in a class can come in any order. See p.253 Big C++ Implicit and Explicit parameter The object on which a member function is applied is the implicit parameter. Every member function of a class has an implicit parameter. Explicit parameters of a member function are listed in the function definition. See p.238 Big C++ Whenever you refer to a data field inside a member function, it denotes that data field of the object for which the member function was called. See p.238 Big C++ One member function can invo ke another member function on it s implicit parameter. See p.251 Big C++ If you see a function call without the dot notation inside a member function, you first need to check whether that function is actually another member function of the same class. If so, it means call this member function with the same implicit parameter. . See p.252 Big C++ y State of an Object Each object of a class stores certain values that are set in the constructor and that may change through the application of mutator functions. These values are collectively called the state of the object. Accessing Data Fields Only member functions of a class are allowed to access the private data fields of objects of that class. All other functions - that is, member functions of other classes

and functions that are not member functions of any class - must go through the public interface of the class. Suppose x is an object of the class SampleClass, privateData belongs to the private data fields of SampleClass and publicData belogs to the public data fields of SampleClass. We may use: x.publicData But cannot use: x.privateData The private data fields are only accessible to member functions of the class.

Member function definition return_type ClassName function_name(parameter1, parameter2, , parameter n) [const]opt { statements }

Constructor definition ClassName ClassName(parameter1, parameter2, { statements }

, parametern)

Calling Constructors from Constructors Suppose we have a non-default constructor of a class which contains objects in the data field. Before the non-default constructor start initializing those objects, the default constructors of the class in which those object belongs are automatically invoked. In fact, the objects will be initialized an d then those values are overwritten. It would be more efficient if we use the following code:

ClassName ClassName(parameters):field 1(expression), { statements } ie. Point Point(double xval, double yval):x(xval), y(yval) { }

, field n(expression)

This syntax is also necessary to construct objects of classes that don t have a default constructor. See p.247 - 248 Big C++ Operator Overloading ie. bool Product operator>(Product b) const { } p.249 Big C++

Comparing member functions and Non -member functions Inside main or another non-member function, it is easy to differentiate between member function calls and other function call. Member functions are invoked using the dot notation; non -member functions don t have an object preceding them. Inside member functions, ho wever, it isn t as simple. One member function can invoke another member function, and here the dot notation is not obvious, as the object is an implicit parameter.

Separate Compilation (Header File + Source Code File - common) The header file contains: (a) Definition of classes (b) Declaration of constants (c) Declarations of non-member functions (global functions) (d) Declarations of global variables

The source files (common) contains: (a) Definitions of member functions & constructors (b) Definitions of non -member functions (c) Definitions of global variables The main function is not contained in the source file (common) as there are many potential programs that might make use of the class. Suppose we have a class MyClass which is contained in the header file myclass .h Programs that need to use MyClass must include the directive: #include myclass.h

The following directives are used (in the header file) to guard against the multiple inclusion of the header file myclass.h: #ifndef MYCLASS_H #define MYCLASS_H

#endif

These directives are needed because compiler sees the class definition twice, and it complains about two classes with the same name. (Sadly, it doesn t check whether the definition are identical.) y How to produce an .exe
g++ -c sourceFile.cpp g++ -o Program.exe source1.o source2.o source3.o Compiles a single source file into an object file Links a series of object files into a single executable. -o means "output" and is a filename

followed by

Vectors A vector is a collection (sequence) of data items of the same type. Every element of the collection (sequence) can be accessed separately.

Syntax: vector<type_name> variable_name; vector<type_name> variable_name(initial_size); eg. vector<int> scores; vector<double> salaries(10); Note: The first slo t of a vector has an index of 0. Trying to access a slot that does not exist in the vector is a serious error. This i s known as bounds error. The compiler does not catch this type of error and the running program generates no error message. Instead, the program will quietly corrupt some memory.

Syntax (for accessing an element in a vector) vector_expression[integer_expression]; When a vector is defined without a size parameter, it is empty and can hold NO elements. For example, the following codes with cause an error. vector<double> salaries; //No size given salaries[0] = 35000; In the size of a vector is not given, we have to use the function push_back. This function allows you to start out with an empty vector and grow the vector. eg. vector<double> salaries; salaries.push_back(value or expression); The push_back command resizes the vector by adding one element to its end. Another member function of the class vector is pop_back. It removes the last element of a vector, shrinking its size by one. eg. vector<double> salaries(10);

salaries.pop_back();

//Now salaries has size 9

Note that the pop_back function does not return the element that is being removed. If you want to know what that element is, you need to capture it first. To visit all the elements in a vector, we can use: for(i = 0; i < v.size(); i++){ do something with v[i]; } Finally, note that vectors are passed by values by default. We can use & if we would like to pass by reference. See p.276 Big C++

Note: An uninitialized integer vector has values zero stored. ie. vector<int> num(3); //the 3 elements of the vector is zero. y Vector as parameters Pass by value return_type function_name(vector<type_name> variable_name, ); Pass by reference return_type function_name(vector<type_name>& variable_name, .); Pass by constant reference return_type function_name(const vector<type_name> variable_name, ); y What are Strings? The term, string, is used in C to describe a contiguous sequence of characters terminated by and including the first null character. [2] A common misconception is that a string is an array, because string literals are converted to arrays during the compilation (or translation) phase. [3] It is important to remember that a string ends at the first NUL byte. An array or string literal that contains a null character before the last byte of the array or string literal is not a string. http://en.wikipedia.org/wiki/C_string

Strings and Characters

The values of type char are enclosed in single quotes, ie H Strings are essentially vectors of characters. Strings are enclosed in double quotes. ie. string greeting = Hello cout greeting[3]; //This gives the character l

Note: An individual character can be stored in one byte. A string, even if it has a length of 1, needs to store both the contents and the length, which requires several bytes. y Converting Characters to Uppercase The toupper function is defined in the cctype header. It converts lowercase characters to uppercase. ie. cout y

toupper( h ); //This gives the character H

Array Arrays, like vectors, is also a collection of elements of the same type. But are of a lower level. Syntax type_name variable_name[size]; eg. int scores[20]; An array can also be initialized as it is declared. int scores[] = {20, 30, 12, 5, 61}; Note that when you supply initialization values, you don t need to specify the array size. The compiler determines the size by counting the values. Unlike a vector, an array can never change size. You cannot use push_back function to add more elements to it. Furthermore, the size of the array has to be known when the program is compiled. That is, you can t ask the user how many elements are needed and then allocate a sufficient number, as you would with a vector. You must also keep a companion variable that counts how many elements are actually used.

Array assignments are INVALID, ie. array1 = array2; is a compilation ERROR. Also, only constants can be used to declare the size of automatic and s tatic arrays. Not using a constant for this purpose is a compilation error. See p.206 C++ How to Program Note: the variable name is a pointer to the starting element of the array. ie. int a[3] = {9, 6, 8}; Here a is a pointer to the first element of the array. However, a[n] is not a pointer. It is an identifier for the element in the array with index n. p.322 Big C++ int a[] = {5, 8, 25}; cout << a << endl; //Show that a is a pointer cout << *a << endl; //Show that a contains the address of the starting element of the int array int b[] = {9, 6, 3}; a = b; //Invalid. Compilation error since a is a pointer with a constant value.

Pointer Arithmetic Pointers into arrays support pointer arithmetic. That is, a + n is a pointer to the element in the array with index n. Also, a[n] == *(a + n); p.322 Big C++

Function with array parameter When writing a function with an array parameter, you place an empty [] behind the parameter name. eg. double maximum(double a[], int a_size);

Unlike all other parameters, array parameters are always passed by reference. You never use an & when defining an array parameter. Although arrays can be function parameters, they cannot be function return types. Also see p.217 C++ How To Program

Character Arrays #include <iostream> using namespace std; int main(){ char charArray[] = {'a', 'b', 'c'}; char str1[] = "abc"; char str2[] = {'a', 'b', 'c', ' \0'}; cout << "charArray[] = " << charArray << "\n"; cout << "str1[] = " << str1 << "\n"; cout << "str2[] = " << str2 << "\n"; for(int i = 0; charArray[i] != '\0'; i++){ cout << charArray[i] << ' '; } cout << endl; for(int i = 0; str1[i] != ' \0'; i++){ cout << str1[i] << ' '; } cout << endl; for(int i = 0; str2[i] != ' \0'; i++){ cout << str2[i] << ' '; }

return 0; } /*

C:\Users\User\Desktop>g++ -Wall array.cpp C:\Users\User\Desktop>a charArray[] = abc #` str1[] = abc str2[] = abc abc? abc abc */ y Cout for Arrays Cout do not provide similar output processing capabilities for other arrays (arrays that are not char arrays). int a[3] = {8, 9 , 10}; string b[3] = {"x", "y", "z"}; char c[3] = {'p', 'q', 'r'}; cout << a << endl; //This shows that a is a pointer cout << b << endl; //This shows that b is a pointer cout << c << endl; //This shows that cout provide a different output processing capability for char arrays cout << *c << endl; //This shows that c is still a pointer C:\Users\User\Desktop>a 0x22ff00 0x22fef4 pqr > p char* ptr1 = "Harry"; char* ptr2 = "John"; cout << ptr1 << end cout << ptr2; Harry John See p.214 C++ How to program y Double Quote The double quote returns a pointer to the first character of the null terminated character array. cout << *"Harry"; //This shows that Harry gives a pointer

H p.327 - 328 Big C++ y c_str() String object is different to string literal and string literal is different to character array. A character array is an array of characters. A string literal is a null terminated array of characters. String object is not just a null terminated character array, it is an object. It can be thought of a class containing the null terminated array with member functions. Member functions can be applied on the string object. The member function c_str() turns a string object into char* pointer to the first character in the null terminated character array. y string(pointer to first element of a character array) This converts the pointer to a string object. y Looking at c_str and string(charArray_pointer). Let ptr be a pointer to the first element of a character array. Let str be a string object.

See p.328 Big C++

y y

strcpy(charArray_pointer1, charArray_pointer 2) strlen(charArray_pointer)

use #include <cstring>

Lvalues and Rvalues Expressions that refer to memory locations are called l-value expressions. An lvalue represents a storage region s locator value, or a left value, implying that it can appear on the left of the equal sign ( =). L-values are often identifiers. All l-values are r-values but not all r-values are l-values. http://msdn.microsoft.com/en-us/library/aa266358%28v=vs.60%29.aspx

Vectors and Arrays Difference

In C++, arrays are contiguous pieces of memory. They are somewhat like blocks aligned together, each block is then given a number, and to look at the contents of each block one only has to supply the number of the block. All the elements of an array must be of the same type. A vector is similar to a dynamically allocated array but with the ability to resize itself, and without the need for manual deallocation of memory. http://en.wikipedia.org/wiki/Vector_%28C%2B%2B%29

READ CHAPTER 7 --------------------y Derived Class Derived Class Definition class DerivedClassName : public BaseClassName{ public: private:

}; All member functions and data member of the base class are automatically inherited by the Derived Class. It is important to note that private data members of the base class are present in each derived-class object, but they are not accessible by member fu nctions of the derived class. Since these fields are private data of the base class, only the base class has access to them. The derived class has no more access rights than any other class. Note: Forgetting the keyword public when defining the derived cl ass will cause everything in the base class to be private.

Derived Class Constructor Syntax DerivedClassName DerivedClassName(expressions) : BaseClassName(expressions){ statements; }

Note: if you omit the base -class constructor, then the base object is constructed with the default constructor of the base class. p.350 Big C++ y Assigning Derived Class object to Base Class object We can assign a derived class object to a base class object. ie. baseClassObject = derivedClassObject; However, all derived-class information is lost in the process, that is simply sliced away. p.357 Big C++ When converting a derived class object to a base class, the derived class data is sliced away. p.357 Big C++ Note we cannot assign a base class object into a derived class variable. p.363 Big C++ y Assigning Derived Class pointer to a Base -Class pointer

Assigning a derived class pointer to a base class pointer is perfectly legal. The reverse assignment - from a base class pointer to a derived class pointer is an error. p.358 Big C++ Note: a pointer is the starting address of an object, therefore pointers to both base and derived class objects should be the same size. p.358 Big C++ y Virtual The virtual keyword must be used in the base class. All functions with the same name and parameter types in derived classes are then automatically virtual. However, it is considered good taste to supply the virtual keyword for the derivedclass functions as well. p.359 Big C++ You do NOT supply the keyword virtual in the function definitions. p.359 Big C++ Whenever a virtual function is called, the compiler determines the type of the implicit parameter in the particular call at run time. The appropriate function for that object is then called. p.360 Big C++ Only member functions can be virtual. p.360 Big C++ class ClassName{ .. virtual return_type function_name(parameter, ); .. };

C++ Standard Library C++ Standard Library is a collection of classes and functions. The C++ Standard Library is divided into many portions, each with its own header file. Each portion can contain more than one class. The header files contain the function prototypes for the related functions that form each portion of the library. The header files also contain definitions of various class types and functions, as well as constants needed by those functions. (Note: each portion of the standard library is also called the library by some people, as seen in the next section) , See Small C++ How to program p.154

C++ Standard Library


y y y y y

C standard library
y y y y y y
<assert.h> <complex.h> <ctype.h> <errno.h> <fenv.h> <float.h> <inttypes.h> <iso646.h> <limits.h> <locale.h> <math.h> <setjmp.h> <signal.h> <stdarg.h> <stdbool.h> <stddef.h> <stdint.h> <stdio.h> <stdlib.h> <string.h> <tgmath.h> <time.h> <wchar.h> <wctype.h>

ios iostream iomanip fstream sstream Standard Template Library

y y y y y y y y y y y y y y y

y y y y y y y y y y y

vector deque list map set stack queue bitset algorithm functional iterator

C++0x
y y

y y y

unordered_map unordered_set

C Standard Library (these are the equivalents to those of the C standard library, their .h versions are still acceptable)
y y y y y y

cassert cctype cerrno climits clocale cmath

y y y y y y y y y y y

csetjmp csignal cstdarg cstddef cstdio cstdint cstdlib cstring ctime cwchar cwctype

The C++ Standard Library includes 18 header files from the C Standard Library with names ending in ".h", but their use is deprecated. [5] All other headers in the C++ Standard Library do not end in ".h". http://en.wikipedia.org/wiki/C%2B%2B_Standard_Library y iostream (header file) iostream is one of the Standard C++ library header files. The following class declarations are found in the iostream header file: ios, iostream, istream, ostream, streambuf THESE ARE CLASSES http://cpp.comsci.us/etymology/include/iostream.html [Note that iostream can mean the header file or the class depending on the context.] The get, getline, and operators are defined for istream objects.

See http://cpp.comsci.us/etymology/include/iostream.html & p.379 Big C++

The put, write, and

operators are defined for ostream objects.

http://cpp.comsci.us/etymology/include/iostream.html#class & p.380 Big C++ The iostream class is derived from both istream and ostream. See p.380 Big C++

fstream (header file) fstream is one of the Standard C++ library header files. http://msdn.microsoft.com/en-us/library/a7tkse1h(v=VS.80).aspx The following class declarations are found in the fstream header file: filebuf, fstreabase, ifstream, ofstream, fstream THESE ARE CLASSES [Note that fstream can mean the header file or the class depending on the context.] http://cpp.comsci.us/etymology/include/fstream.html#class

The fstream library defines stream class types ifstream, ofstream, and fstream. Class ifstream is derived from the class istream. http://www.adiwebs.com/use-of-fstream-library-in-c/

The ifstream class derves from the istream class. See p.379 Big C++ ------------------------------------------------------------An istream is a source of bytes. An ostream is a destination of bytes. p.379 - 380 Big C++

Hierarchy of Stream Classes istream header: iostream operators: get,getline, and variables: cin ostream header: iostream operators: put, write, and variables: cout, cerr, clog

istringstream header: sstream

ifstream header: fstream

iostream header: iostream

ofstream jeader: fstream

ostringstream header: sstream

Note: open function is a member of ifstream class NOT istream class.

SCREEN (require header: iostream) cin cout cin x; cout y;

FILE (require header: fstream) ifstream cinfile; cinfile.open( file.dat ); ofstream coutfile; coutfile.open( file.dat ); cinfile x; //Read a word coutfile y; getline(cinfile, s); //Read a line char ch; cinfile.get(ch); //Read a character cinfile.unget(); //Unget a character coutfile.put(ch); //To write a single character cinfile.close(); coutfile.close();

STRING (require header: sstream) istringstream cinstring(str); ostringstream coutstring; cinstring x; coutstring y; coutstring.str(); //to retrieve the string

Note: string something; something string; Note .open( ) takes a character pointer. We can use the c_str() function to convert a string into a character pointer. ie. string.c_str();

.get(ch) is a member function of the base class istream. It removes one character from the stream. See p.377 Big C++ A file variable must be pass by reference. See p.378 Big C++

---------------------------------------

Stream Manipulators library: include <iomanip> We have setw, setfill, setprecision, fixed, left, right. All are sticky EXCEPT setw. Also by default: we have setfill( ), that is, by default the space is the fill character. Also by default, we have alignment to the right.

Command Line Arguments In the command line: prog -v input.dat Source code int main(int argc, char* argv[]){ } Note that: string(argv[0]); //gives the string prog string(argv[1]); //gives the string -v string(argv[2]); //gives the string input.dat

Rando

ort random access the cin and cou streams which are attached Only dis file s to the keyboard and the terminal, do not. ach disk file has two s ecial positions the get position and the put position.

Get position At first, the get position is at the start position. ut position At first, the put position is at the start position. -----------------fstrea fs; fs.open test.dat ); To mo e the get o put positions: fs.seekg(n ios beg); OR fs.seekg(n ios end); fs.seekp(n ios beg); OR fs.seekp(n ios end);

Note here n is the number of spaces away from the start or end position. ie. if we would like it to move one space to the right, make n e ual to 1. -----------------

In a data file the ne line character \n c (Confirmed by myself)

  

Access nts as two characters in a .dat file.

To find the get or put : fs.tellg(); fs.tellp(); These two functions returns the number of spaces after the start position. ie. if the get or put is at 4 , the returned value will be 1.

Operator Overloading The programmer is permitted to define new meanings for operators only if at least one argument has a class type. A programmer cannot, for example, change the meaning of the addition operator when it is used with integer arguments. The language has a predefined set of operators, and the user is not allowed to create new ones. In addition, the precedence and associativity among operators is fixed by the language and cannot be changed. Also, with the exception of the function call operator, the number of arguments required for each operator is fixed and cannot be changed.

Operator Function Declaration return_type operatoroperator_symbol(parameters);

Operator Function Definition return_type operatoroperator_symbol(parameters){ } Operator Member Function Declaration class ClassName{ .. return_type operatoroperator_symbol(parameters); .. }; Operator Member Function Definition return_type ClassName operatoroperator_symbol(parameters){ .. } Note: Nonmember Function version: implicit type conversion will be performed for both left and right arguments. Member Function version: implicit type conversion for the right argument only. See p.550 Big C++ Note: There are two categories of type conversions to consider for overloaded operators. 1) Conversion of a type to the new user -defined class. Conversion of this type is handled using constructors. If we do not want a constructor to be used for implicit conversion, add the keyword explicit in front of the prototype of the constructor in the class definition. 2) Conversion from the user -defined class to another type. Conversion of this type is accomplished by a conversion operator, which uses a type as the operator name. ie. ClassName operator type_name(){ .. }

The conversion operator uses type as the operator name, has no arguments, and does not specify a result type (since the result type is implicit in the name). y Assignment Operator The assignment operator is automatically generated when a class is created, should the programmer not override it. The default implementation will assign all data fields, a process termed a member-wise assignment. This is normally what we want. See p.568 Big C++

However, operators +=, *=, and the like are NOT automatically generated. ------------------------y exit(1); exit belongs to #include <cstdlib>. It terminates the program like assert(). However, it does NOT print statements like assert(). Also exit returns a value. See p.671 Big C++ y Exceptions logic_error is a standard exception class that is declared in the #include <stdexcept>. Throwing an Exception throw expression; eg. (1) logic_error description( reason ); //initialize a logic_error object called description throw description; (2) throw logic_error( reason ); The keyword throw indicates that the function exits immediately. It then searches the caller, the caller s caller, and so forth, for a handler that specifies how to handle the error.

Catching Exceptions try{ codes } catch(type_name variable_name){ statements } catch(type_name variable_name){ statements } If any function in the try clause throws an exception, or call another function that throws an exception. The search process described above for a handler begins. We must be careful when trying to catch the exception thrown. Note that implicit conversion, such as from int to double, or from char* to string, are not performed when trying to catch a thrown exception. ie. reason cannot be catch by catch(string e). char* cannot be catch by catch(string e).

Throw user-defined objects class my_error   public: my_error(string reason); }; my_error my_error(string reason) : logic_error( reason){}

REVISION EXERCISES

HAVE TO READ 2D ARRAY AND POINTERS TO FUNCTION Exercise 2 division by 0, produces a run-time error. Q17 A C-string (that is, a null terminated character array) contains a null character at the end. But the function strlen(s) will find the length without the null character. Exercise 7 dereferencing a NULL pointer will cause the program to crash, but the program still compiles. Q1 dereferencing an uninitialized pointer or a deleted pointer is just a logic error (run-time error), the program still compiles and DOES NOT crash. cout NULL; will display 0 as NULL is converted to zero. Q14 int a[3] = {5, 6, 9}; int* ptr = a; cout << ptr[2]; The code above is perfectly ok. See Q23 Redo Q9 Exercise 8 The purpose of inheritance is to model similar objects with different behaviour. Q7 Polymorphism implementation depends on virtual member functions, class inheritance, function overloading. Q15

Vous aimerez peut-être aussi