תכנות מכוון עצמים ושפת ++C וויסאם חלילי. TODAY TOPICS: 1. Function Overloading & Default Parameters 2. Arguments By Reference 3. Multiple #include’s 4.

Slides:



Advertisements
Similar presentations
Chapter 6 Advanced Function Features Pass by Value Pass by Reference Const parameters Overloaded functions.
Advertisements

Files 1 יום חמישי 16 אפריל 2015 יום חמישי 16 אפריל 2015 יום חמישי 16 אפריל 2015 יום חמישי 16 אפריל 2015 יום חמישי 16 אפריל 2015 יום חמישי 16 אפריל 2015.
Templated Functions. Overloading vs Templating  Overloaded functions allow multiple functions with the same name.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Pointers הרצאה קריטית. השאלות הפתוחות מה זה ה- & שמופיע ב scanf מדוע כשמעבירים מחרוזת ל scanf אין צורך ב & האם ניתן להכריז על מערך שגדלו אינו ידוע בתחילת.
תכנות מונחה עצמים Object Oriented Programming (OOP) אתגר מחזור ב'
C++ Pointer and Functions
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
1 6/20/2015CS150 Introduction to Computer Science 1 Functions Chapter 6, 8.
1 מבוא למדעי המחשב מבנה של תכנית. 2 מבנה של תכנית – חלוקה לקבצים  תכנית בשפת C הינה אוסף של הגדרות של:  משתנים (חיצוניים)  פונקציות  ניתן לפרוש תכנית.
תכנות מונחה עצמים Object Oriented Programming (OOP) אתגר מחזור ב' Templates תבניות.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Overview scope - determines when an identifier can be referenced in a program storage class - determines the period of time during which that identifier.
Pass by Reference. COMP104 Pass by Reference / Slide 2 Passing Parameters by Reference * To have a function with multiple outputs, we have to use pass.
CSE 332: C++ functions Review: What = and & Mean In C++ the = symbol means either initialization or assignment –If it’s used with a type declaration, it.
Recap, Test 1 prep, Composition and Inheritance. Dates Test 1 – 12 th of March Assignment 1 – 20 th of March.
C++ function call by value The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter.
CS 11 C++ track: lecture 4 Today: More on memory management the stack and the heap inline functions structs vs. classes.
ITEC 320 C++ Examples.
Multiple Files. Monolithic vs Modular  one file before  system includes  main driver function  prototypes  function.
Array in C++ / review. An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred.
CSIS 113A Lecture 8 Parameters.  Two methods of passing arguments as parameters  Call-by-value  ‘copy’ of value is passed  Call-by-reference  ‘address.
11 Introduction to Object Oriented Programming (Continued) Cats.
1 Command-Line Processing In many operating systems, command-line options are allowed to input parameters to the program SomeProgram Param1 Param2 Param3.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
Week 2. Functions: int max3(int num1, int num2, int num3) {int result; result = max(max(num1,num2),num3); return result; } //max3.
Functions Sujana Jyothi C++ Workshop Day 2. Functions 3 Parameter transmission modes pass by value (default) pass by reference (&) pass by const reference.
1 More Operator Overloading Chapter Objectives You will be able to: Define and use an overloaded operator to output objects of your own classes.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
11 Introduction to Object Oriented Programming (Continued) Cats.
1 Reference Variables Chapter 8 Page Reference Variables Safer version of C/C++ pointer. "Refers to" a variable. Like a pointer. Effectively.
CMSC 202 Lesson 6 Functions II. Warmup Correctly implement a swap function such that the following code will work: int a = 7; int b = 8; Swap(a, b); cout.
מבנים קרן כליף. ביחידה זו נלמד :  מהו מבנה (struct)  איתחול מבנה  השמת מבנים  השוואת מבנים  העברת מבנה לפונקציה  מבנה בתוך מבנה  מערך של מבנים.
AL-HUSEEN BIN TALAL UNIVERSITY College of Engineering Department of Computer Engineering Object-Oriented Programming Course No.: Fall 2014 Templates.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
CS1201: Programming Language 2 Function I By: Nouf Aljaffan Edited by : Nouf Almunyif.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
Lecture 01d: C++ review Topics: functions scope / lifetime preprocessor directives header files C structures ("simple classes")
1 Compiler directive: #define, usage 1 #include using namespace std; #define TAX //double TAX=0.08; #define LAST_NAME "Li" #define FIRST_NAME "Dennis"
Lecture 9 – Array (Part 2) FTMK, UTeM – Sem /2014.
Current Assignments Project 3 has been posted, due next Tuesday. Write a contact manager. Homework 6 will be posted this afternoon and will be due Friday.
C++ Functions A bit of review (things we’ve covered so far)
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
LECTURE 3 PASS BY REFERENCE. METHODS OF PASSING There are 3 primary methods of passing arguments to functions:  pass by value,  pass by reference, 
#define #include<iostream> using namespace std; #define GO
IF-ELSE כתוב תוכנית הקולטת שלושה מספרים ומדפיסה אותם בסדר עולה(ממיינת אותם)  קלט:7,2,4 ,פלט:2,4,7 .
Object Oriented Programming
Programmer-Defined Functions, Call-by-Value, Multiple Files Lab 5
Pointers and Pointer-Based Strings
מצביעים קרן כליף.
תכנות מכוון עצמים ו- C++ יחידה 01 מ- C ל- C++
סוגי משתנים קרן כליף.
Pointers & Functions.
תוכנה 1 תרגול 13 – סיכום.
תכנות מכוון עצמים ו- C++ יחידה 02 העמסת פונקציות, ערכי ברירת מחדל, enum, קימפול מותנה קרן כליף.
CS150 Introduction to Computer Science 1
Dynamic Memory A whole heap of fun….
Classes.
C++ Compilation Model C++ is a compiled language
Pointers and Pointer-Based Strings
foo.h #ifndef _FOO #define _FOO template <class T> class foo{
Functions Lecture 5.
Pointers & Functions.
The Stack.
CMSC 202 Lesson 6 Functions II.
CS1201: Programming Language 2
Class rational part2.
Functions Chapter No. 5.
Presentation transcript:

תכנות מכוון עצמים ושפת ++C וויסאם חלילי

TODAY TOPICS: 1. Function Overloading & Default Parameters 2. Arguments By Reference 3. Multiple #include’s 4. Inline Functions

void foo(int i, int j)} //foo1 cout << "I'm the foo that returns void" << endl; } void foo(int i, int j=1)} //foo2 cout << "I'm the foo that returns void with default parameter" << endl; } void foo(int i)} //foo3 cout << "I'm the foo that returns void with one parameter" << endl; } int foo(int i, int j)} //foo4 cout << "I'm the foo that returns int" << endl; return 7; } Function Overloading & Default Parameters

void foo(int i, int j)} //foo1 cout << "I'm the foo that returns void" << endl; } void foo(int i, int j=1)} //foo2 cout << "I'm the foo that returns void with default parameter" << endl; } void foo(int i)} //foo3 cout << "I'm the foo that returns void with one parameter" << endl; } int foo(int i, int j)} //foo4 cout << "I'm the foo that returns int" << endl; return 7; } Function Overloading & Default Parameters אילו פונקציות לא יכולות לחיות יחד ? PitfallFunc2Func1 Default parameterfoo2foo1 Default parameterfoo3foo2 Return valuefoo4foo1 Return valuefoo4foo2

void fun(const char * str)} str = "dd"; str[0]='a'; } void fun(char const * str)} str = "dd"; str[0]='a'; } void fun(char * const str)} str = "dd"; str[0]='a'; } Back to Pointers & const מי מהביטויים חוקי ומי לא ?

void fun(const char * str)} str = "dd"; str[0]='a'; //forbidden: str is a pointer to constant argument } void fun(char const * str)} str = "dd"; str[0]='a'; //forbidden: str is a pointer to constant argument } void fun(char * const str)} str = "dd"; //forbidden: the "str" argument itself is a constant argument str[0]='a'; } Back to Pointers & const

Arguments By Reference void swap(int x, int y)} int temp = x; x=y; y=temp; } void main()} int arr[] = {1, 6, 34, 28, 73}; int size = sizeof(arr)/sizeof(arr[0]); int index1, index2; cout << "This is the array: "; printArr(arr, size); cout : "; cin >> index1 >> index2; swap(arr[index1],arr[index2]); cout << "This is the array after swapping: "; printArr(arr, size); } void printArr(int* arr, int size)} for(int i=0; i<size; i++)} cout << arr[i] << ", "; cout << endl; } קלט : 2,4 פלט : ?

Arguments By Reference void swap(int &x, int &y) } int temp = x; x=y; y=temp; } קלט : 2,4 פלט : 1, 6, 34, 28, 73 תיקון לפונקציה :

Return By Reference EX1 #include using namespace std; // should be int globalVar = -1; int& getGlobalVar() } return globalVar; } void main() } getGlobalVar() = 4; cout << getGlobalVar() << endl; } פלט : ?

Return By Reference EX1 #include using namespace std; // should be int globalVar = -1; int& getGlobalVar() } return globalVar; } void main() } getGlobalVar() = 4; cout << getGlobalVar() << endl; } פלט : 4

Return By Reference EX2 #include using namespace std; // should be int globalVar = -1; int& getGlobalVar() } int i = globalVar; return i; } void main() } getGlobalVar() = 4; cout << getGlobalVar() << endl; } פלט : ?

Return By Reference EX2 #include using namespace std; // should be int globalVar = -1; // this is wrong !!! // can't return local variable ByRef ! // Should be compilation error, but VC++6.0 // accepts it and gives a warning // (anyway it's WRONG) int& getGlobalVar() } int i = globalVar; return i; //warning C4172: returning address of local variable or temporary } פלט : אסור להחזיר reference למשתנה מקומי ( על ה stack)

Return By Reference EX3 #include using namespace std; // should be int globalVar = -1; int& getGlobalVar() } int& i = globalVar; return i; } void main() } getGlobalVar() = 4; cout << getGlobalVar() << endl; } פלט : ?

Return By Reference EX3 #include using namespace std; // should be int globalVar = -1; // here i is a reference to globalVar // and this is fine int& getGlobalVar() } int& i = globalVar; return i; } פלט : 4

Return By Reference EX4 // should be int globalVar = -1; const int& getGlobalVar() } switch(globalVar){ case 1: return 1; case 2: return 2; case 3: return 3; case 4: return 4; case 5: return 5; default: return -1; } return -1; } void main()} globalVar = 4; cout << getGlobalVar() << endl; } פלט : ?

Return By Reference EX4 #include using namespace std; // should be int globalVar = -1; // returning is a number and not variable // warning C4172: returning address of local variable or temporary const int& getGlobalVar() } switch(globalVar){ case 1: return 1; case 2: return 2; case 3: return 3; case 4: return 4; case 5: return 5; default: return -1; } return -1; } פלט : 4

תזכורת : פעולת ה - include פעולת ה - include היא פקודת קדם - מעבד (preprocessor) אשר שותלת בקוד במקום כל פקודת include את תוכן הקובץ שאותו כללנו בפקודה // prototypes void aFoo1(); int aFoo2(); #include #include "a.h" void main() } aFoo1(); aFoo2(); { #include // prototypes void aFoo1(); int aFoo2(); void main() } aFoo1(); aFoo2(); { a.h main.cpp

הבעיתיות בפקודת include יתכן ונעשה include לקובץ מסוים יותר מפעם אחת : #include // prototypes void aFoo1(); int aFoo2(); // prototypes void aFoo1(); int aFoo2(); // prototypes Void bGoo1(); int bGoo2(); void main() } aFoo1(); bGoo1(); { a.h main.cpp // prototypes void aFoo1(); int aFoo2(); #include #include "a.h“ #include “b.h“ void main() } aFoo1(); bGoo1(); { b.h #include “a.h” // prototypes void bGoo1(); int bGoo2(); נקבל שגיאה של redefinition מאחר והקומפיילר רואה את ההצהרה על הפונקציות שמוגדרות ב - a.h יותר מפעם אחת מ - a.h מ - b.h

הפתרון : הידור מותנה ראינו בעבר את הפקודה #define לצורך הגדרת קבוע מסוים פקודה זו מוסיפה את הקבוע שהוגדר לטבלת סימולים של התוכנית במידה וטרם הוגדר. במידה וכבר הוגדר דורסת את ערכו. ניתן גם לכתוב פקודת define ללא ערך, רק כדי להכניס קבוע מסוים לטבלת הסימולים ניתן לבדוק האם קבוע מסוים הוגדר בטבלת הסימולים בעזרת הפקודה #ifdef או אם לא הוגדר בעזרת הפקודה #ifndef –במידה והתנאי מתקיים, הקופיילר יהדר את קטע הקוד הבא עד אשר יתקל ב - #endif

הפתרון עם הידור מותנה #include // prototypes void aFoo1(); int aFoo2(); // prototypes void bGoo1(); int bGoo2(); void main() } aFoo1(); bGoo1(); { a.h main.cpp #ifndef __A_H #define __A_H // prototypes void aFoo1(); int aFoo2(); #endif // __A_H #include #include "a.h“ #include “b.h“ void main() } aFoo1(); bGoo1(); { b.h #ifndef __B_H #define __B_H #include “a.h” // prototypes void bGoo1(); int bGoo2(); #endif // __B_H כעת יש לנו ב - main פעם אחת בלבד את ההגדרות מכל קובץ טבלת הסימולים : __A_H __B_H main.cpp לאחר preprocessor

בעיה נוספת ב - include כאשר יש 2 מבנים אשר כל אחד מגדיר אובייקט מטיפוס המבנה השני, מתקבלת שגיאת קומפילציה שקשה להבינה : טבלת הסימולים : __A_H __B_H #ifndef __A_H #define __A_H #include “b.h” struct A { B b; }; #endif // __A_H #include "a.h“ #include “b.h“ void main() } { #ifndef __B_H #define __B_H #include “a.h” struct B { A a; }; #endif // __b_H הקומפיילר אינו מכיר את הטיפוס A ולכן שגיאת הקומפילציה...

הפתרון במקרה זה נדאג שלפחות אחד המבנים יכיל רק מצביע למבנה השני, ולא אובייקט –כאשר יוצרים אוביקט צריך לבצע include לקובץ המגדיר אותו –כאשר יש מצביע לאובייקט לא חייבים לבצע include לקובץ המכיל אותו, אלא להסתפק בהצהרה שמבנה זה יוגדר בהמשך בקובץ cpp בו תהיה היצירה של האובייקט נבצע את ה - include לקובץ בו מוגדר המבנה #ifndef __A_H #define __A_H #include “b.h” struct A { B b; }; #endif // __A_H #ifndef __B_H #define __B_H struct A; struct B { A* a; }; #endif // __b_H הצהרה שהמחלקה תוגדר בהמשך

Inline #ifndef _INLINE_FUNCTION_H_ #define _INLINE_FUNCTION_H_ #include using namespace std; // this is an example of inline function // (should be in.h file! otherwise you may get linker errors) inline void foo() { cout << "foo" << endl; } #endif #include "inlineFunction.h" void main() { foo(); } inlineFunction.h inlineFunction.cpp

Inline equivalent inline void foo(int startTime, int endTime, int& deltaTime) { deltaTime = endTime - startTime; } void main() { int elapsedTime = 0; foo(21,24,elapsedTime); } void main() { int elapsedTime = 0; { int startTime = 21; int endTime = 24; int& deltaTime = elapsedTime; deltaTime = endTime - startTime; } Inline Function The equivalent