1 / 54

Introduction to C++ Part II Version 1.0

Introduction to C++ Part II Version 1.0. Topics. C++ Functions -- passing by value -- passing by reference -- passing by address reference in C ++ pointer/address in C++ C++ Arrays -- char arrays -- vectors. C++ Functions. What we called methods in C# are referred to

watson
Télécharger la présentation

Introduction to C++ Part II Version 1.0

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to C++Part IIVersion 1.0

  2. Topics C++ Functions -- passing by value -- passing by reference -- passing by address reference in C++ pointer/address in C++ C++ Arrays -- char arrays -- vectors

  3. C++ Functions What we called methods in C# are referred to as functions in C++.

  4. Function Prototypes The C# compiler is a multipass compiler, and so it is not necessary to “declare” a method before it is used. This is not true in C++. In C++, we must declare a function by writing a function prototype in the code someplace before the function is ever called. For stand-alone functions we normally write the function prototypes before main( ).

  5. #include <iostream> using namespace std; void printMe(int); #include “my.h” int main( ) { int a = 5; printMe(a); system("PAUSE"); return 0; } void printMe(int num) { cout << "\nNumber = " << num << endl; } my.h The function prototype Calling the function my.cpp The function implementation

  6. We usually include the function prologue with the function prototype. #include <iostream> using namespace std; // The printMe function // Purpose: outputs the parameter // Parameter: The value to be output as an integer // Returns: nothing void printMe(int); int main( ) { int a = 5; printMe(a); system("PAUSE"); return 0; } void printMe(int num) { cout << "\nNumber = " << num << endl; }

  7. Passing Parameters by Value Passing parameters by value is the same in C++ and C# C++ void swap(intnum1, intnum2) { int temp = num1; num1 = num2; num2 = temp; } C# void swap(intnum1, intnum2) { int temp = num1; num1 = num2; num2 = temp; } int n = 5; int m = 3; swap (n, m); int n = 5; int m = 3; swap (n, m);

  8. Passing Parameters by Reference Passing parameters by reference is slightly different in C++ and C# C++ void swap(int& num1, int& num2) { int temp = num1; num1 = num2; num2 = temp; } C# void swap( ref int num1, ref int num2) { int temp = num1; num1 = num2; num2 = temp; }

  9. Passing Parameters by Reference Passing parameters by reference is slightly different in C++ and C# C++ void swap(int& num1, int& num2) { int temp = num1; num1 = num2; num2 = temp; } C# void swap( ref int num1, ref int num2) { int temp = num1; num1 = num2; num2 = temp; } int n = 5; int m = 3; swap (n, m); int n = 5; int m = 3; swap (ref n, ref m);

  10. In C++, there are no reference types as there are in C#. Everything is passed by value, unless you explicitly tell the compiler to pass by reference.

  11. Passing Parameters by Address Passing parameters by addres is not normally in C# and it is a main stay in C++ C# Normally not allowed! C++ void swap(int* num1, int* num2) { int temp = *num1; *num1 = *num2; *num2 = temp; } int n = 5; int m = 3; swap (&n, &m);

  12. Passing by constReference C++ has a notion of constantness that does not exist in C#. When passing a parameter by reference, it is possible to have a side effect that changes the data in the calling function. Generally side effects are not wanted. To avoid side effects, we pass by constant reference.

  13. void printMe( const Employee& joe); This is a common idiom in C++. It allows us to pass an object without having to make a copy of the object (which is expensive), but avoids any changes to the object by the function.

  14. If a member function does not change anything (for example, a “getter”), then you should make the function a constant function. string Employee::getAddress( ) const;

  15. Arrays in C++

  16. Arrays in C++ There is a major difference in how arrays are defined in C# and C++. In C#, arrays are true objects. In C++ they are not objects just homogeneous collections of data.

  17. 0 1 2 3 4 5 6 7 8 9 An array is a homogeneous list of values … not an object examScores All values must be of the same type (homogeneouse) 89 Values are stored in consecutive memory locations 94 78 93 The position where a value is stored in an array is given by its index. We sometimes refer to this as the subscript. 75 99 82 Indexing always begins with zero 77 53 To access an element of an array, we use the array name, followed by the index inside of square brackets 87

  18. 0 1 2 3 4 5 6 7 8 9 Declaring an Array examScores array size data type of array elements int examScores[10]; the declaration Good programming style uses a constant for the array size. For example const int SIZE = 10; int examScores[SIZE];

  19. 0 1 2 3 4 5 6 7 8 9 Accessing array elements in C++ is identical to C# examScores index address of first element examScores 89 94 78 examScores * 4* int size 93 75 value of examScores[4] 99 82 77 53 87

  20. Out of Bounds Errors When a C++ program is executing, it does not notice when a calculation results in an array index that is out of bounds. The address of the element is calculated and that place in memory is accessed, even if it does not belong to the array! This is much different than what happens in C#.

  21. index 0 0 someInts 1 someInts +4 1 int someInts[5], badNum; badnum = 100; for ( int indx = 0; indx <=5; indx++) { someInts[indx] = indx; } 2 someInts +8 2 3 someInts +12 3 4 someInts +16 4 badNum 100 5 Notice that we over-wrote the variable badNum with the value of 5! This destroys the original value in badNum.

  22. Initializer lists int examScores [ ] = { 87, 83, 94, 99, 74, 66, 88 }; the array size is automatically determined by the number of items in the initializer list

  23. Since an array is not an object, there is no member data nor any methods that return the size of the array. When passing an array as a parameter, it is common to pass the size of the array as an additional parameter. intasize = sizeof(examScores);

  24. Two Dimensional Arrays columns rows How we think of a two dimensional array

  25. examScores 78 89 65 97 student 1 student 2 76 79 82 85 student 3 83 89 91 90 exam 1 exam 2 exam 3 exam 4

  26. An Array of Arrays 78 89 65 97 student 1 student 2 76 79 82 85 student 3 83 89 91 90 exam 1 exam 2 exam 3 exam 4

  27. int main( ) { // declare an array 3 x 4 int examScores[ ][4]= { {78, 89, 65, 97}, {76, 79, 82, 85}, {83, 89, 91, 90} }; const int STUDENT = 3; const int EXAMS = 4; for ( int i = 0; i < STUDENT; i++ ) { int sum = 0; for ( int j = 0; j < EXAMS; j++ ) sum = sum + examScores [ i ][ j ]; float avg = ((float)sum)/EXAMS; cout << “Student # “ << (i+1) << “: “ << avg << “\n”; } }

  28. Multi-dimensional array as a parameter… We do not give the size of the first dimension of an array when passing it, but we do give the sizes of the remaining dimensions. The size of the first dimension is passed as a separate argument. void getPage (char p[][100], intsizeOne);

  29. Char Arrays We have been using the C++ String class to represent strings of characters. Although this is the most convenient way to represent character strings, the C++ language also represents character strings as arrays of type char.

  30. someText The terminal character in the array is the null terminating character, \0. 0 h This is called a null terminated string, or a C-string (this is the only way that a character string could be represented in the C language). 1 e 2 l l 3 4 o Functions that operate on C-strings look for the null terminating character to know where the end of the string is. 5 \0 When creating an array to store a character string, always be sure that there is room for the null terminating character.

  31. firstName J 0 lastName o 1 S 0 h 2 m 1 n 3 i 2 \0 4 t 3 ? 5 h 4 ? ? 5 ? ? . . . ? . . . Note that is possible to have an array of characters that is not a C-String. char firstName[20] = “John”; when initialized this way, the null terminating character is automatically added at the end. char lastName[20] = {‘S’,’m’,’i’,’t’,’h’}; when initialized this way, no null terminating character is added. This is just a simple array of characters. It is not a C-String!

  32. Char Arrays and Loops You can treat a char array exactly like any other array. You can use index notation to access individual array elements lastName[n] = ‘ t ’; You can use loops to manipulate arrays elements. for (int n = 0; n < SIZE; n++) { lastName[n] = ‘ - ’; } But … be careful not to accidentally replace the null terminating character with some other character.

  33. Assignment Although you can use the assignment operator when initializing an array, you cannot use the assignment operator anywhere else with a character array. For example, the following is illegal: char aString[10]; aString = “Hello”;

  34. strcpy Function The easiest way to assign a value to a C-String is to use the strcpy function. To use strcpy you must use the include directive #include <cstring> No using statement is required, the definitions in <cstring> are in the global namespace.

  35. Security Issues Incorrect use of string functions has caused many security problems because of buffer over-runs. To prevent these problems use: “n” versions of functions, like strncpy – you must ensure that string is null-terminated. If it is not, do it manually after the copy. “l” versions of functions, like strlcpy – these are not part of the standard library, but source code is available from BSD “_s” versions of functions, like strcpy_s – available with Microsoft development tools, might be included in standard libraries later.

  36. Examples strcpy (aString, “Hello”); copies the char string Hello into aString. includes a null terminating character. strcpy (aString, bString); copies the contents of bString into aString. by making the last parameter one less than the size of aString, you can make the copy safe … i.e. it will not over-run the array. strncpy (aString, bString, 9); copies at most 9 characters from bString into aString.

  37. Equality Comparing two C-Strings using the equality operator will compile without errors and will execute, but will not give you the results you expect. char aString[ ] = “abc”; char bString[ ] = “abc”; if ( aString == bString ) { …

  38. strcmp Function To compare two C-Strings, use the strcmp function. You must #include <cstring> to use this function. strcmp(strng1, strng2); returns a value of zero if the strings are equal returns a negative value if strng1 < strng2 returns a positive value if strng1 > strng2 comparison is done in lexicographic order.

  39. Other <cstring> functions strcat (strng1, strng2); concatenates strng2 to the end of strng1. strlen (aString); returns the length of aString does not include the null terminating character

  40. C-String Input and Output You can use >> and << operators to input and output C-Strings. To input a string containing blanks, you must use cin.getline (a, n); where a is a char array and n is an integer that indicates the max number of characters to read. Note that the null terminating character fills one of these character positions.

  41. These techniques work on files as well as standard input and output.

  42. Character I/O Sometimes it is useful to input and output one character at a time. cin.get(aChar); reads one character into aChar. cout.put (aChar); writes the character in aChar to cout. These work on any character, including spaces and new-line characters.

  43. Example The following code will read one character at a time from standard in and write it to standard out, until a new-line character is encountered. char symbol; do { cin.get (symbol); cout.put (symbol); } while (symbol != ‘\n’);

  44. Character Manipulation Functions The following functions operate on characters. To use any of these you must #include <cctype> No using statement is required. The definitions in <cctype> are in the global namespace.

  45. The ASCII Code Table

  46. toupper (aChar); returns the upper case value of aChar as an integer. tolower (aChar); returns the lower case value of aChar as an integer. islower (aChar); returns true of the value in aChar is lower case. isalpha (aChar); returns true if the value in aChar is a letter.

  47. isdigit (aChar); returns true if the value in aChar is a digit 0 through 9 isspace (aChar); returns true if the value in aChar is white space.

  48. Vectors Vectors can be thought of as arrays that grow as required, while a program is executing. Vectors are formed from a template class in the Standard Template Library (STL).

  49. Declaring a Vector #include <vector> using namespace std; . . . vector <int> v; the notation <int> defines the type of vector. In this case, we have declared a Vector of integers.

  50. Accessing Vector Elements You can use the square bracket notation [ ] to access elements of a vector, just as you do for an array. Note however, that you can only access existing Vector elements this way, you cannot initialize them!

More Related