Introduction to OOP. - ee.bgu.ac.iladcomplab/oop/Documents... · Introduction to OOP. ... value –...

51
11/9/2014 DSP lab 1 Introduction to OOP. Presented by: Any fool can write code that a computer can understand. Good programmers write code that humans can understand. (Martin Fowler) בס'' ד11/9/2014 2 Contents: History; C refrain; The OOP basis; Getting started.

Transcript of Introduction to OOP. - ee.bgu.ac.iladcomplab/oop/Documents... · Introduction to OOP. ... value –...

11/9/2014

DSP lab 1

Introduction to OOP.

Presented by:

Any fool can write code that a computer can understand.

Good programmers write code that humans can understand.

(Martin Fowler)

ד''בס

11/9/2014 2

Contents:

History;

C refrain;

The OOP basis;

Getting started.

11/9/2014

DSP lab 2

ד''בס

11/9/2014 4

The C and C++ development

C – was developed from BCPL and B languages. The

languages hasn’t different types definition, so each

variable (char, short or long) is stored as one cell

(word) in physical memory. However, the C language

is a program language with different build-in types

C++ - C based program language which was

developed in Bell laboratory in the beginning 80’s.

The C++ is support OOP (Object Oriented

Programming)

ד''בס

Why C++?

11/9/2014 5

a

b

11/9/2014

DSP lab 3

ד''בס

What are the memory segments?

The text segment (often

called code segment) is

where the compiled code of

the program itself resides.

The two other sections from

the code segment in the

memory are used for data

11/9/2014 13

ד''בס

What is stack?

The stack is the section of memory that is allocated

for automatic variables within functions. • declaration with no static or external specifier defines an automatic

variable

Data is stored in stack using the Last In First Out (LIFO)

method. This means that storage in the memory is

allocated and deallocated at only one end of the memory

called the top of the stack.

Stack is a section of memory and its associated registers

that is used for temporary storage of information in which

the most recently stored item is the first to be retrieved. 11/9/2014 14

11/9/2014

DSP lab 4

ד''בס

What is heap?

Heap is an area of memory used for dynamic

memory allocation. Blocks of memory are

allocated and freed in this case in an arbitrary

order. The pattern of allocation and size of blocks

is not known until run time.

Heap is usually being used by a program for many

different purposes.

11/9/2014 15

ד''בס

What is heap and stack?

The stack is a place in the computer memory

where all the variables that are declared and

initialized before runtime are stored

The heap is the section of computer

memory where all the variables created or

initialized at runtime are stored.

The stack is much faster than the heap but also

smaller. 11/9/2014 16

11/9/2014

DSP lab 5

ד''בס

What is heap and stack?

11/9/2014 17

int x; // static stack storage

void main() {

int y; // dynamic stack storage

char str; // dynamic stack storage

str = malloc(50); // allocates 50 bytes of

// dynamic heap storage

size = calcSize(10); // dynamic heap storage,

// if function defined

// in DLL

ד''בס

11/9/2014 18

Arrays and Pointers Static array:

– are allocated on the stack.

int iFibArray[10];

int k;

iFibArray[0] = 1;

iFibArray[1] = 1;

for (k = 2; k < 10; k++)

iFibArray[k] = iFibArray[k - 1] +

iFibArray[k - 2];

11/9/2014

DSP lab 6

ד''בס

11/9/2014 19

Dynamic Memory Allocation The static arrays allocates on the stack which has a limited

size.

When large arrays are needed we have to use dynamic memory allocation. Using this way the arrays allocates on the heap

int n;

int *iArrayP;

n = 1000;

iArrayP = (int *) malloc (sizeof(int) * n);

if (iArrayP == NULL)

abort(); /* In case the allocation has failed */

iArrayP[n-1] = 1;

:

Free (iArrayP);

ד''בס

11/9/2014 20

Arrays and Pointers

A pointer is a variable whose size is the same as the size of int and can store the address of another variable

float fSum; // definition of a variable

float *fSumP; // definition of a pointer

fSumP = NULL; // - i.e. the pointer is currently not

// pointing on any variable

fSumP = &fSum; // fSumP obtains the address of fSum

fSum = *fSumP; // de-reference a pointer or i.e. obtain

// the variable in that address

11/9/2014

DSP lab 7

ד''בס

11/9/2014 21

Arrays and Pointers Pointers play important role when passing parameters

to functions.

void swap (int a,

int b)

{

int temp = a;

a = b;

b = temp;

}

void main()

{

int x = 3, y = 4;

swap(x, y);

}

void swap (int *aPtr,

int *bPtr)

{

int temp = *aPtr;

*aPtr = *bPtr;

*bPtr = temp;

}

void main()

{

int x = 3, y = 4;

swap(&x, &y);

}

• The function on the

left don’t really change

the values of x and y.

• In C function

arguments are passed by

value – copy each

function argument to

stack.

• The solution is to pass

the address of the

variables to the function.

ד''בס

11/9/2014 22

Compound data types It is possible to expand the data type repository by

defining structures. A structure is used to pack together

several fields that are conceptually related:

struct Date

{

int iDay;

int iMonth;

int iYear;

} DataStr;

// Structure objects

definition

struct Date date;

date.iDay = 31;

date.iMonth = 12;

date.iYear = 1999;

// Pointer to structure

struct Data *dateP = &date;

(*dateP).iDay = 21;

// or easier

dateP->iDay = 21;

11/9/2014

DSP lab 8

ד''בס

11/9/2014 23

Compound data types It is very convenient to define enumeration types. An

enumeration variable is an integer, which have a limited range of designated values:

By default the first enum value is 0, and each next is 1 more then previous, but It’s possible to assign different integer values:

enum ChessBoardColour

{

Black;

White

};

enum ChessBoardColour col;

:

If (col == Black)

{

:

};

enum _ErrorCode

{

AllOK = 1;

FileNotFound = -1;

IllegalFileFormat = -2;

}

ד''בס

11/9/2014 24

Compound data types By default the first enum value is 0, and each next is 1 more then

previous, but It’s possible to assign different integer values:

It’s possible to use the typedef command in order to define more

convenient name for our data types:

enum _ErrorCode

{

AllOK = 1;

FileNotFound = -1;

IllegalFileFormat = -2;

}

typedef enum _Errorcode Errorcode;

11/9/2014

DSP lab 9

ד''בס

11/9/2014 25

Recursion

In C function can call itself. The following

function calculates recursively the value of n!:

int factorial (int n)

{

if (n <= 0)

return(1);

else

return(n*factorial(n-1));

}

ד''בס

11/9/2014 26

Variable scope

Local variable is defined inside a function and destroyed then function terminates

– the variable created in the stack

Global variables are created before the first instruction in the main. It is executed and destroyed only after the program terminates

– the variable created on the data segment

The keyword static before global variable and function makes it available only within the file It is defined in.

11/9/2014

DSP lab 10

ד''בס

11/9/2014 27

Variable scope The keyword static before a variable declaration

inside a function:

– the variable created the first time the function is called and isn’t destroyed when it terminates

The keyword register before a variable declaration inside a function. The register variables may be only local.

– the variable created in the CPU register

The keyword volatile before a variable declaration behaves like register. It prevents optimization operations on variable. However allows to allocate variable on the memory instead of register.

– the variable created in the memory

ד''בס

11/9/2014 29

C vs. C++

Same syntax, operators, expressions, data

types, structures, arrays, cycles, functions

and pointers;

C++ has some new keywords:

– class, delete, friend, inline, new, protected,

public and et.

C++ supports object oriented programming

11/9/2014

DSP lab 11

ד''בס

11/9/2014 30

Introduction to OOP

עצמים בתור אותנו הסובב העולם את תופסים אנו ,בית ,מכונית ,פרח ,כלב ,ציפור :למשל ,(אובייקטים)

.'וכו אדם

משקל ,צבע ,צורה ,גודל :למשל ,מאפיינים יש עצם לכל .'וכו

שמאפיינות (פונקציות ,מתודות) פעולות יש עצם לכל ',וכו לאכול ,לדבר ,לנוע יכול אדם העצם :למשל .אותו

.'וכו הדרך את להאיר ,לצפצף ,לנוע יכול מכונית העצם

המאפיינים על צפייה כדי תוך העצמים על לומדים אנו .לבצע יכולים שהם הפעולות ועל

ד''בס

11/9/2014 31

Introduction to OOP עצמים מונחה תכנות (Progamming Oriented Object, OOP) הוא

את ממדל הוא – האדם מוח פועל שבה לזו דומה בצורה הפועל תכנות .עצמים בעזרת "העולם"

לרכז ניתן (לכמס, encapsulate) השייכים והפונקציות המאפיינים כל את .שמו על (class) למחלקה מסויים לעצם

עצם בין היחס (object) ומחלקה (class) עוגה לתבנית עוגה בין היחס הוא.

פעולות או/ו משותפים מאפיינים בעלי להיות יכולים שונים עצמים זאת למרות) לנוע יכולים מכונית העצם וגם אדם העצם גם למשל .משותפות

.(המכונית מתנועת שונה האדם תנועת

האבות" יהיו יותר כלליים עצמים ,עצמים של היררכי מבנה להגדיר ניתן" חלק להם (inherit ,להוריש) לתת ויוכלו פחות כלליים עצמים של

שכן ציפור מהעצם מאפיינים לקבל יכול תוכי העצם למשל .מתכונותיהם .ציפור של סוג הוא תוכי

11/9/2014

DSP lab 12

ד''בס

11/9/2014 32

The major properties of OOP

ריכוזיות - Encapsulation / מידע הסתרת – hiding Information

של תיפקודו לשם הדרושים (ונתונים קוד) המשאבים כל של מחלקתית ההכלה לפרסם רוצה העצם אותו ,לממשק להגיע רק יכולים אחרים עצמים .העצם

העצם למשל .פנימית בצורה נעשים דברים איך לדעת יכולת להם אין אך ,כלפיהם האדם כלומר) המכונית העצם של (נסיעה) התנועה בפעולת להשתמש יכול אדם .זה בעצם המנוע פועל איך להבין בלי (במכונית לנסוע יכול

תורשה - Inheritance

צורך אין זו בצורה .ממנה הנגזרת למחלקה אחת ממחלקה משאבים של העברה .הנגזרת ולמחלקה הבסיס למחלקת שמשותפות תכונות על פעמים כמה לחזור .רהיט מהמחלקה נגזרת שולחן המחלקה :למשל

צורתיות ריבוי - Polymorphism

עבור המתבצעות זהה שם עם פעולות עבור שונות משמעויות להקנות היכולת המדובר העצם אם שונה משמעות מקבלת "פתיחה" פעולת :למשל .שונים עצמים

.שימורים קופסת הוא המדובר שהעצם או דלת הוא

ד''בס

Input/Output

Notes: – cin & >> and cout << Both operators can be applied sequentially,

and are left associative;

– One can send any type of basic data type to cout or obtain it from cin;

– It is possible to differentiate between normal program output, which is sent to cout, and error output, which is sent to ceer (similar to stdout and stderr in C);

– The endl is a global manipulator, and means end of line (endl = “\n”)

using namespace std;

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

int n, fact;

cin >> n;

fact = factorial(n);

cout << n << “! = “ << fact << endl;

11/9/2014

DSP lab 13

ד''בס

Structures vs. Classes Working with complex numbers in C:

struct _Complex

{

float re // The real part.

float im; // The imaginary part

};

typedef struct _Complex Complex;

#include <math.h>

/* Calculate the amplitude and

argument of Complex number */

double magnitude (Complex z)

{

return(sqrt

(z.re*z.re+z.im*z.im));

}

double argument (Complex z)

{

return(atan2 (z.im, z.re))

}

Working with complex numbers in C++:

class Complex

{

private:

float Re // The real part.

float Im; // The imaginary part

pablic:

// Get the real and imaginary part

float getReal() {return (Re);}

float getImag() {return (Im);}

// Set the complex number x + iy

void set (float x, float y);

{

Re = x;

Im = y;

}

};

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

Complex z;

z.set(3,4);

cout << “z= “ << z.getReal();

cout << “+i”<< z.getImeg()<<endl;

z.Re = 5; ERROR!!! is a private data

ד''בס

Function Overloading

C++ supports writing more than one function with the same name but different argument lists. This could include:

– different data types

– different number of arguments

The advantage is that the same apparent function can be called to perform similar but different tasks. The following will show an example of this.

11/9/2014

DSP lab 14

ד''בס

Function Overloading void swap (int *a, int *b) ;

void swap (float *c, float *d) ;

void swap (char *p, char *q) ;

int main ( )

{

int a = 4, b = 6 ;

float c = 16.7, d = -7.89 ;

char p = 'M' , q = 'n' ;

swap (&a, &b) ;

swap (&c, &d) ;

swap (&p, &q) ;

}

void swap (int *a, int *b)

{ int temp; temp = *a; *a = *b; *b = temp; }

void swap (float *c, float *d)

{ float temp; temp = *c; *c = *d; *d = temp; }

void swap (char *p, char *q)

{ char temp; temp = *p; *p = *q; *q = temp; }

ד''בס

11/9/2014 43

Example 1: The class definition and the

advantages of Encapsulation

מחלקה (class) מאפיינים להכיל יכולה והיא העצם של התבנית היא .העצם של פונקציותו

הרשאות משלוש אחת לקבל יכולים והפונקציות המשתנים:

•Public – וגם מתוך גם אלו ולמשתנים לפונקציות נגישות יש .לעצם מחוץ

•Private – העצם מתוך רק אלו ולמשתנים לפונקציות נגישות יש, כעמיתים שמוגדרים לעצמים רק אלא ,לו מחוצה לא אך

(friends).

•Protected – ומתוך העצם מתוך נגישות יש .ביניים השראת העצם של נגזרותיו מתוך נגישות יש כן כמו שלו העמיתים

.שלהם והעמיתים

11/9/2014

DSP lab 15

ד''בס

11/9/2014 44

Example 1: The class definition and the

advantages of Encapsulation

הבונה פונקציות (Constructor) פונקצייה היא בדרך .העצם יצירת עם אוטומטית שנקראת מחלקתית

משתני את לאתחל מנת על זו בפונקציה משתמשים כלל לשמה זהה שם בעלת היא הבונה פונקציית .המחלקה

.המחלקה של

המפרק פונקציות (Destructor) פונקציה היא .העצם פירוק עם אוטומטית שנקראת מחלקתית

פונקציית .(התוכנית בסוף למשל מתרחש העצם פירוק) אך ,המחלקה של לשמה זהה שם בעלת היא המפרק

.שמה לפני ~ הסימן בעלת היא

1 // Time class.

2 #include <iostream>

3 #include <iomanip>

4 using namespace std;

5

6

7

8

9 // Time class definition

10 class Time {

11 public:

12 Time(); // constructor

13 void setTime( int, int, int ); // set hour, minute, second

14 void printTime(); // print universal-time format

15

16 private:

17 int hour; // 0 - 23 (24-hour clock format)

18 int minute; // 0 - 59

19 int second; // 0 - 59

20

21 }; // end class Time

class Time-הגדרת ה

נתונים

ופונקציות

בעלי הרשאה

ציבורית

נתונים ופונקציות

בעלי הרשאה פרטית

11/9/2014

DSP lab 16

Constructor initializes private data members

to 0.

23 // Time constructor initializes each data member to zero and

24 // ensures all Time objects start in a consistent state

25 Time::Time()

26 {

27 hour = minute = second = 0;

28 } // end Time constructor

29

30 // set new Time value using universal time, perform validity

31 // checks on the data values and set invalid values to zero

32 void Time::setTime( int h, int m, int s )

33 {

34 hour = ( h >= 0 && h < 24 ) ? h : 0;

35 minute = ( m >= 0 && m < 60 ) ? m : 0;

36 second = ( s >= 0 && s < 60 ) ? s : 0;

37 } // end function setTime

38

39 // print Time

40 void Time::printTime()

41 {

42 cout << setfill( '0' ) << setw( 2 ) << hour << ":"

43 << setw( 2 ) << minute << ":" << setw( 2 ) << second;

44 }// end function printTime field width

פונקציית הבונה מאתחלת נתון

0-ל (private)בעל הרשאה פרטית

בדיקת תקינות

נתונים בעלי הרשאה

(private)פרטית

פונקציית

בנאי

פונקצייה

לשינוי

הזמן

פונקצייה

להדפסת

הזמן

fill

character field

width

45 int main()

46 {

47 Time t; // instantiate object t of class Time

48

49 // output Time object t's initial value

50 cout << "The initial time is ";

51 t.printTime(); // 00:00:00

52

53 t.setTime( 13, 27, 6 ); // change time

54

55 // output Time object t's new values

56 cout << "\n\nThe time after setTime is ";

57 t.printTime(); // 13:27:06

58 cout << endl;

59

60 return 0;

61 } // end main

להיות tהצהרה על המשתנה

class-אובייקט מטיפוס ה

Timeהנקרא

שימוש בפונקציית חבר בעל

(public)הרשאה ציבורית

כדי להדפיס את הזמן

שימוש בפונקציית חבר בעל

(public)הרשאה ציבורית

כדי לשנות את הזמן

The initial time is 00:00:00

The time after setTime is 13:27:06

11/9/2014

DSP lab 17

ד''בס

11/9/2014 48

((x,yנקודה

x,y))

x

y

((x,y,r,hגליל אליפסי

((x,y,rעיגול

x,y))

x

y r

((x,y,x1,y1קו ((x,y,x1,y1קו

x,y))

x

y

x1,y1))

Example 2: Inheritance לפי תכונת התורשה ניתן

של מבנה היררכילבנות .עצמים

Base class – מספק נתונים פונקציות או

.ים אחרים-class-ל

Derived class – יורש נתונים או פונקציות

.ים אחרים-class-מ

יורש את גלילהעצם :דוגמא עיגולתכונותיו של העצם

שיורש את תכונותיו של העצם העצם : מצד שני. נקודהמוריש את תכונותיו גם נקודה .קווגם לעצם עיגוללעצם

((x,y,r,hגליל

x,y))

r h

File point.h:

1 #ifndef POINT_H

2 #define POINT_H

3

4 class Point {

5 public:

6 Point( int = 0, int = 0 ); // default constructor

7 void setX( int ); // set x in coordinate pair

8 int getX() const; // return x from coordinate pair

9 void setY( int ); // set y in coordinate pair

10 int getY() const; // return y from coordinate pair

11 void print() const; // output Point object

12

13 protected:

14 int x; // x part of coordinate pair

15 int y; // y part of coordinate pair

16 }; // end class Point

17

18 #endif

Class

definition בעלי הרשאה ציבורית

(public)

בעלי הרשאה מוגנת

(protected)

.שלא הייתה קיימת בדוגמא הקודמת cpp.-ו h.שימו לב לחלוקה לקבצים : הערה

Keyword const will

ban getX(), getY() and

print() in class Point from

being anything which can

attempt to alter any member

variables in the object

11/9/2014

DSP lab 18

1 #include <iostream>

2 #include "point.h" // Point class definition

3 // default constructor

4 Point::Point( int xValue, int yValue )

5 {

6 x = xValue;

7 y = yValue;

8 } // end Point constructor

9 // set x in coordinate pair

10 void Point::setX( int xValue )

11 {

12 x = xValue; // no need for validation

13 } // end function setX

14 // return x from coordinate pair

15 int Point::getX() const

16 {

17 return x;

18 } // end function getX

19 // set y in coordinate pair

20 void Point::setY( int yValue )

21 {

22 y = yValue; // no need for validation

23 } // end function setY

24 // return y from coordinate pair

25 int Point::getY() const

26 {

27 return y;

28 } // end function getY

29 // output Point2 object

30 void Point::print() const

31 {

32 cout << '[' << x << ", " << y << ']';

33 } // end function print

File point.cpp:

Constructor

function

פונקציה

xלשינוי

פונקציה

yלשינוי

פונקציה

xלקבלת ערכו של

פונקציה

yלקבלת ערכו של

Printing x

& y

1 #ifndef CIRCLE_H

2 #define CIRCLE_H

3

4 #include "point.h" // Include point class definition

5

6 class Circle : public Point {

7

8 public:

9 // default constructor

10 Circle ( int = 0, int = 0, double = 0.0 );

11 void setRadius( double ); // set radius

12 double getRadius() const; // return radius

13 double getArea() const; // return area

14 void print() const; // output Circle object

15

16 private:

17 double radius; // Circle's radius

18

19 }; // end class Circle

20 #endif

File circle.h:

Connection to

the base

class

בעלי הרשאה ציבורית

(public)

בעלי הרשאה פרטית

(private)

נקודה class-ה

מוריש את תכונותיו

עיגול class-ל

11/9/2014

DSP lab 19

1 #include <iostream>

2 #include "circle.h" // Include circle class definition

3

4 // default constructor

5 Circle::Circle( int xValue, int yValue, double radiusValue )

6 {

7 x = xValue;

8 y = yValue;

9 setRadius( radiusValue );

10 } // end Circle constructor

11 // set radius

12 void Circle::setRadius( double radiusValue )

13 {

14 radius = ( radiusValue < 0.0 ? 0.0 : radiusValue );

15 } // end function setRadius

16 // return radius

17 double Circle::getRadius() const

18 {

19 return radius;

20 } // end function getRadius

21 // calculate and return area

22 double Circle::getArea() const

23 {

24 return 3.14159 * radius * radius;

51 } // end function getArea

25 // output Circle object

26 void Circle::print() const

27 {

28 cout << "Center = [" << x << ", " << y << ']'

29 << "; Radius = " << radius;

30 } // end function print

File circle.cpp

פונקציית

בנאי

פונקצייה

לשינוי

הרדיוס

פונקצייה

לקבלת השטח

פונקצייה לקבלת

ערכו של הרדיוס

הדפסת

x ,y והרדיוס

מאחר והם y -ו x ניתן לשנות את

-protected הוכרזו כ

Point)הנקרא ) –Base classב

פונקציית הבנאי קוראת

לפונקציית ( באופן מוסתר(

Base class -הבנאי של ה

y -ו x -ניתן להשתמש ב

מאחר והם הוכרזו

Base class-ב-protected כ

Point)הנקרא )

1 #include <iostream>

2 #include <iomanip>

33 #include "circle.h" // Circle class definition

44

55 int main()

66 {

77 Circle MyCircle( 37, 43, 2.5 ); // instantiate Circle object

99 // display point coordinates

10 cout << "X coordinate is " << MyCircle.getX()

11 << "\nY coordinate is " << MyCircle.getY()

12 << "\nRadius is " << MyCircle.getRadius();

13

14 MyCircle.setX( 2 ); // set new x-coordinate

15 MyCircle.setY( 2 ); // set new y-coordinate

16 MyCircle.setRadius( 4.25 ); // set new radius

17

18 // display new point value

19 cout << "\n\nThe new location and radius of circle are\n";

20 MyCircle.print();

21

22 // display Circle's area

23 cout << "\nArea is " << MyCircle.getArea();

25 cout << endl;

27 return 0; // indicates successful termination

29 } // end main

X coordinate is 37

Y coordinate is 43

Radius is 2.5

The new location and radius of circle are

Center = [2, 2]; Radius = 4.25

Area is 56.74

File CircleTest.cpp:

Output after executing

MyCircleיצירת האובייקט

שימוש בפונקציות

על Point-שנורשו מ

מנת לגשת לנתונים

xו- y( הם בהרשאת

protected )

י שימוש "קבלת הרדיוס ע

של getRadiusבפונקציה

MyCircle

שימוש בפונקציות שנורשו

על מנת לשנות את Point-מ

y -ו xהנתונים

( protectedהם בהרשאת )

שימוש בפונקציה

setRadius שלMyCircle

על מנת לשנות את נתון

שהוא בעל השראת )הרדיוס

private)

Print שימוש בפונקציה

על מנת MyCircleשל

להדפיס את נתוני העיגול

getArea שימוש בפונקציה

על מנת להדפיס MyCircleשל

את נתוני העיגול

11/9/2014

DSP lab 20

ד''בס

11/9/2014 54

זיכרון דינאמי הוא חלק חשוב בשביל כמעט כל המתכנתים בעולם; ++C מספקת לנו שני אופרטורים בזיכרון דינאמי:

–new - זיכרון ומחזיר פוינטר להתחלה( תופס)מאתר; – delete- י "משחרר את הזיכרון שאותר מקודם עnew;

אופרטורים אלו משמשים לתפוס זיכרון ולשחרר זיכרון בזמן ריצה (.פעולה)למרות שC++ בפונקציות י''עתומכת בהקצאת זיכרון דינאמי גם

malloc ו-free ,נהוג להשתמש באופרטורים new ו-delete ;שהיא חלק C נכללות בגלל שפת free-ו mallocפונקציות

.++Cמשפת יתרונות שלnew:

בצורה אוטומטית מאתר מספיק זיכרון בכדי להחזיק אובייקט מסוג –מכוון שהגודל מותאם , sizeofלא צריך להשתמש באופרטור . ספציפי

אוטומטית אוטומטית מחזיר פוינטר לאותו סוג ספציפי–

Dynamic memory

1 #include <iostream.h>

2 #include <new.h>

3 int main ( )

4 {

5 int *ptr; 6 // memory allocation for variable with size int

7 ptr = new int;

8 *ptr = 100;

9 cout<<“At" << ptr <<" "; 10 cout<<" is the value " << *ptr <<"\n";

11 delete ptr;

12 return 0;

13 }

At 0xabcdef00 is the value 100

ptr = new Type;

delete ptr;

11/9/2014

DSP lab 21

ד''בס

11/9/2014 56

Memory allocation for arrays

1 #include <iostream.h>

2 #include <new.h>

3 int main ( )

4 {int *array, i; 5 // memory allocation for array of integers with length 10

6 array = new int [10];

7 for ( i = 1; i < 10; i++) 8 {

9 *array++ = i;

10 cout << array[i] << "\n";

11 }

12 delete [] array;

13 return 0;

14 }

1

2

3

4

5

6

7

8

9

10

ptr = new Array_Type[Size];

delete [ ] ptr;

ד''בס Pass by Pointer and pass by

Reference in C++

11/9/2014 57

// Illustration of pass

by pointer

#include <iostream.h>

void square (int *x)

{

*x = (*x)*(*x);

}

int main ( )

{

int num = 10;

square(&num);

// Value of num is 100

cout << " Value of num is

"<< num;

return 0;

}

// Illustration of pass by reference

#include <iostream.h>

// x becomes a reference parameter

void square (int &x)

{

// no need to write *x = (*x)*(*x);

x = x * x;

}

int main ( )

{

int num = 10;

square(num);

// Value of num is 100

cout << "Value of num is “ << num;

return 0;

}

11/9/2014

DSP lab 22

ד''בס

More about reference variables

11/9/2014 58

Reference variables are not applicable only to function parameters.

You can have them in other places of the program as well. Consider

the following program:

#include <iostream.h>

int main( )

{

int x;

int &ref = x; //ref is a reference variable

x=5;

cout << endl << x << " “ << ref;

x++;

cout << endl << x << " “ << ref;

ref++;

cout << endl << x << " “ << ref;

cout << endl << &x << endl << &ref;

return 0;

}

The reference variables provides different names same variable. They both refers to

the same memory address. The address of both ‘ref’ and ‘x’ is the same.

5 5

6 6

7 7

0x0065FDF4

0x0065FDF4

ד''בס

11/9/2014 59

המצביע ,הפולימופיזם תכונת לפי יכול Base Class-ל הרפרנס או

כאשר שונות בדרכים להתנהג

.מרובה בשימוש נמצא הוא לגשת למשל נוכל זו בצורה

במקום הנגזר class-ב לפונקציה .הבסיס class-ב לפונקציה

ב-C++ שימוש תוך נעשה הדבר

מה) וירטואליות בפונקציות

של הפולימורפיות את שיגדיר

.(העצם

Example3: Polymorphism

Pet

Dog Cat

Functions:

1. Breath

2. Speak

Example

11/9/2014

DSP lab 23

1 #include <iostream>

2 #include <string>

3

4 class Pet

5 {

6 public:

7 // Constructors, Destructors

8 Pet () {}

9 virtual ~Pet () {}

10

11 // General methods

12 void breath();

13 virtual void speak();

14 };// end class pet

15

16 void Pet::breath()

17 {

18 cout << “Gasp" << endl;

19 }

20

21 void Pet::speak()

22 {

23 cout << "Growl" << endl;

24 }

Pet

Dog Cat

"חיית מחמד"הגדרת המחלקה

ופונקציית פונקציות בנאי1.

וירטואליתהורס

פונקציית נשימה 2.

וירטואליתפונקציית דיבור 3.

פונקציית

נשימה

פונקציית

דיבור

In object-oriented programming, a

virtual function or virtual method is a

function or method whose behavior can

be overridden within an inheriting class

by a function with the same name

1 class Dog: public Pet

2 {

3 public:

4 Dog() {}

5

6 void speak();

7 };

8 void Dog::speak()

9 {

10 cout << “Hav-Hav" << endl;

11 }

12 class Cat: public Pet

13 {

14 public:

15 Cat() {}

16

17 void speak();

18 };

19 void Cat::speak()

20 {

21 cout << "Meow" << endl;

22 }

23 void chorus(Pet pet, Pet *petPtr, Pet &petRef)

24 {

25 pet.speak(); petPtr->speak(); petRef.speak();

28 }

Pet

Dog Cat

שיורשת " כלב"הגדרת המחלקה

"חיית מחמד"את המחלקה

פונקציות בנאי 1.

חדשהפונקציית דיבור . 2

(פונקציית נשימה הורשה כבר)

חדשהפונקציית דיבור

המחליפה את " כלב"למחלקה

פונקציית הדיבור הישנה של

"חיית מחמד" Class-ה

חדשהפונקציית דיבור

המחליפה את " חתול"למחלקה

פונקציית הדיבור הישנה של

"חיית מחמד"המחלקה

שיורשת " חתול"הגדרת המחלקה

"חיית מחמד"את המחלקה

פונקציות בנאי 1.

חדשהפונקציית דיבור . 2

(פונקציית נשימה הורשה כבר)

"מקהלה"הפונקציית

מקבלת את האובייקט

מצביע , "חיית מחמד"

אליו ורפרנס אליו קבלת רפרנס לעצם קבלת מצביע לעצם קבלת העצם

11/9/2014

DSP lab 24

1 int main()

2 {

3 Pet *ptr; //Pointer to base class

4

5 ptr = new Pet; cout << "Pet Created" << endl;

6 cout << "Pets singing" << endl;

7 chorus(*ptr,ptr,*ptr);

8 cout << endl << endl;

9 delete ptr; //Prevent memory leaks

10

11 ptr = new Dog; cout << “Dog Created" << endl;

12 cout << “Dogs singing" << endl;

13 chorus(*ptr,ptr,*ptr);

14 cout << endl << endl;

15 delete ptr; //Prevent memory leaks

16

17 ptr = new Cat; cout << "Cat Created" << endl;

18 cout << “Cats singing" << endl;

19 chorus(*ptr,ptr,*ptr);

20 cout << endl << endl;

21 delete ptr; //Prevent memory leaks

22 return 0;

23 } //End main

Pet Created

Pets singing

Growl

Growl

Growl

Dog Created

Dogs singing

Growl

Hav-Hav

Hav-Hav

Cat Created

Cats singing

Growl

Meow

Meow

יצירת אובייקט חדש יצירת מצביע למחלקת הבסיס

ptrואיתחול המצביע

כך שיצביע עליו

יצירת אובייקט חדש

ptrואיתחול המצביע

כך שיצביע עליו

יצירת אובייקט חדש

ptrואיתחול המצביע

כך שיצביע עליו

*ptr = אובייקט

ptr = מצביע

*ptr = אובייקט

ptr = מצביע

*ptr = אובייקט

ptr = מצביע

רפרנס מצביע אובייקט

רפרנס מצביע אובייקט

רפרנס מצביע אובייקט

הארגומנט כמו) "by value" ארגומנט מעבירים כאשר• של העתק למעשה מועבר (המקהלה פונקציית של הראשון

.ארגומנט אותו העצם עבור שמספיק מקום מכין הקומפיילר זה במצב•

"כלב" העצם את לתוכו להעתיק מנסה ואז "מחמד חיית" ."(חתול" או)

מתבצע "מחמד חיית" מהעצם גדולים אלו שעצמים מכיוון• של או) "כלב" העצם של החלק שרק כך ,(slicing) חיתוך .יעותק "מחמד חיית" לעצם הזהה "(חתול" העצם

פונקציית ,זו במקרה הדיבור לפונקציית קוראים כאשר• .שתופעל זו היא "מחמד חיית" העצם של הדיבור

פונקציית של והשלישי שני הארגומנט של במקרים• רפרנס / (כתובת) פוינטר מעבירים כאשר ,המקהלה

העצם של או) "כלב" העצם של הדיבור פונקציית מופעלת ."(חתול"

את איפשרנו ,כוירטואלית הדיבור פונקציית הכרזת עקב• של הרפרנסים או המצביעים של הפולימורפית ההתנהגות

להגיע בעזרתם ניתן כלומר – "מחמד חיית" הבסיס מחלקת .ממנה הנגזרות המחלקות של הדיבור לפונקציית

Pet Created

Pets singing

Growl

Growl

Growl

Dog Created

Dogs singing

Growl

Hav-Hav

Hav-Hav

Cat Created

Cats singing

Growl

Meow

Meow

11/9/2014

DSP lab 25

ד''בס

function y = mean(x)

% MEAN Average or mean value.

% For vectors, MEAN(x) returns the mean value.

% For matrices, MEAN(x) is a row vector

% containing the mean value of each column.

[m,n] = size(x);

if m == 1

m = n;

end

y = sum(x)/m;

Structure of a Function M-file

Online Help

MATLAB

Code

Output Argument(s)

Function Name (same as file name .m)

Input Argument(s)

Keyword: function

»output_value = mean(input_value) Command Line Syntax

ד''בס

What are MEX-files?

MEX stands for MATLAB Executable.

MEX-files are a way to call your custom

C/C++ routines directly from MATLAB as

if they were MATLAB built-in functions.

Mex-files can be called exactly like M-

functions in MATLAB.

Here, all code examples will be presented in

C.

11/9/2014 66

11/9/2014

DSP lab 26

ד''בס

Reasons for MEX-files

The ability to call large existing C/C++

routines directly from MATLAB without

having to rewrite them as M-files.

Speed: you can rewrite bottleneck

computations (like for-loops) as a MEX-file

for efficiency.

11/9/2014 67

ד''בס

The gateway routine The name of the gateway routine must be

mexFunction.

– prhs - an array of right-hand input arguments.

– plhs - an array of left-hand output arguments.

– nrhs - the number of right-hand arguments, or the size

of the prhs array.

– nlhs - the number of left-hand arguments, or the size of

the plhs array.

11/9/2014 69

void mexFunction (int nlhs, mxArray *plhs[],

int nrhs, const mxArray *prhs[])

{

/* more C/C++ code ... */

{

11/9/2014

DSP lab 27

ד''בס

Some important points The parameters prhs, plhs, nrhs and nlhs are

required.

„ The header file, mex.h, that declares the entry

point and interface routines is also required.

The name of the file with the gateway routine will

be the command name in MATLAB.

The file extension of the MEX-file is platform

dependent.

– The mexext function returns the extension for the

current machine

MATLAB is 1-based and C is 0-based

11/9/2014 71

ד''בס

EXAMPLE: hellomatlab.c The function description:

– If a string is passed as an input, it displays the string as output

– If no inputs are passed, a default string is passed as an output

– An improper call (improper number of inputs/outputs) returns an error

message as the output

11/9/2014 72

/* hellomatlab.c */

# include "mex.h"

void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray

*prhs[])

}

if (nrhs < 1)

plhs[0] = mxCreateString("Default String: Hello Users");

else if (nrhs > 1)

mexErrMsgTxt("Improper Inputs argument: Please pass 1 or no

input arguments");

else

plhs[0] = mxDuplicateArray(prhs[0]);

{

11/9/2014

DSP lab 28

ד''בס

C compiler http://www.mathworks.com/support/compilers/R2013b/index.html?

sec=win64

11/9/2014 73

ד''בס

EXAMPLE: hellomatlab.c Setup the C-compiler to generate MEX-files

Compile the hellomatlab.c and build the binary MEX-file

Call the hellomatlab function with one input argument. See the results.

Call the hellomatlab function without inputs.

Call the hellomatlab function with improper number of inputs

11/9/2014 74

/* hellomatlab.c */

1.>> mex –setup

2.>> mex hellomatlab.c

3.>> hellomatlab (['My first MEX-file works!'])

ans = My first MEX-file works!

4.>> hellomatlab

ans = Default String: Hello Users

5.>> hellomatlab (['My first MEX-file works!'],['aaa'])

Error using hellomatlab

Improper Inputs argument: Please pass 1 or no input

arguments

11/9/2014

DSP lab 29

ד''בס

THE mex SCRIPT SYNTAX mex –help displays the help file for mex

mex –setup select or change the compiler

configuration

mex filenames compiles and links one or more

C/C++ source files specified in filenames into a

shared library called a binary MEX-file from

MATLAB.

mex options filenames compiles and links one or

more source files specified in filenames using one

or more of the specified command-line options

11/9/2014 75

ד''בס

Working with mxArrays

[a,b]=timestwo([1 2 3 4; 5 6 7 8], 8)

11/9/2014 76

/* timestwo.c */

#include "mex.h"

void mexFunction(int nlhs, mxArray

*plhs[], int nrhs, const mxArray

*prhs[])

{

int i, j, m, n;

double *data1, *data2;

if (nrhs != nlhs)

mexErrMsgTxt("The number of input

and output arguments must be the

same.");

for (i = 0; i < nrhs; i++)

{

/* Find the dimension of the data */

m = mxGetM(prhs[i]);

n = mxGetN(prhs[i]);

/* Create an mxArray for the output */

plhs[i] = mxCreateDoubleMatrix(m,

n, mxREAL); /* Get the data passed in */

data1 = mxGetPr(prhs[i]);

/* Create an array for the output's

data */

data2 = (double *) mxMalloc(m*n *

sizeof(double));

/* Put data in the array */

for (j = 0; j < m*n; j++)

data2[j] = 2 * data1[j];

/* Assign the data array to the output array */

mxSetPr(plhs[i], data2);

}

}

11/9/2014

DSP lab 30

ד''בס

Working with integers

11/9/2014 77

int index;

index=(int)mxGetScalar(prhs[1]);

ד''בס

An additional examples

11/9/2014 78

#include "mex.h"

void timestwo(double y[], double x[])

{ y[0] = 2.0*x[0]; }

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])

{ double *x, *y; int mrows, ncols; /* Check for proper number of arguments. */

if (nrhs != 1)

{ mexErrMsgTxt("One input required."); }

else if (nlhs > 1)

{

mexErrMsgTxt("Too many output arguments");

} /* The input must be a noncomplex scalar double.*/

mrows = mxGetM(prhs[0]);

ncols = mxGetN(prhs[0]);

if (!mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) || !(mrows == 1 && ncols == 1))

{

mexErrMsgTxt("Input must be a noncomplex scalar double.");

} /* Create matrix for the return argument. */

plhs[0] = mxCreateDoubleMatrix(mrows,ncols, mxREAL); /* Assign pointers to each input and output. */

x = mxGetPr(prhs[0]); y = mxGetPr(plhs[0]); /* Call the timestwo subroutine. */ timestwo(y,x); }

11/9/2014

DSP lab 31

ד''בס

An additional examples

11/9/2014 79

#include "mex.h“

void timestwo_alt(double *y, double x)

{ *y = 2.0*x; }

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])

{

double *y;

double x;

/* Create a 1-by-1 matrix for the return argument. */

plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);

/* Get the scalar value of the input x. */

/* Note: mxGetScalar returns a value, not a pointer. */

x = mxGetScalar(prhs[0]); /* Assign a pointer to the output. */

y = mxGetPr(plhs[0]); /* Call the timestwo_alt subroutine. */

timestwo_alt(y,x); }

ד''בס On-line help for mex file in

MATLAB For on-line help support it need to create an m-file

with the same name as mex-file.

The function should be decelerated and help body

should be written, but no function body.

The file should be saved as m file with same name

as function.

11/9/2014 80

% timestwo.m

function [out1,out2] = timestwo(in1,in2)

% timestwo takes 2 arguments and returns 2 …

11/9/2014

DSP lab 32

ד''בס

Simple GUI examples

11/9/2014 82

http://webee.technion.ac.il/control/info/Projects/Students/2010/Mi

chal%20Yemini%20and%20Moria%20Drukman/WWW/MATLA

B%20GUI%20Tutorial%20-%20For%20Beginners.htm

http://www.mathworks.com/videos/creating-a-gui-with-guide-

68979.html

ד''בס

MATLAB GUI

http://webee.technion.ac.il/control/info/Proj

ects/Students/2010/Michal%20Yemini%20a

nd%20Moria%20Drukman/WWW/MATL

AB%20GUI%20Tutorial%20-

%20For%20Beginners.htm

http://www.mathworks.com/videos/creating

-a-gui-with-guide-68979.html

11/9/2014 83

11/9/2014

DSP lab 33

ד''בס

11/9/2014 85

The Editor – provides an interactive environment for you to create and edit C++

source code,

– editor also provides color cues to differentiate between various language elements

The Compiler – converts your source code into object code, and detects and reports

errors in the compilation process;

– The object code output from the compiler is stored in files called object files. The object code usually have name with the extension .obj.

The Linker – The linker combines the various modules generated by the

compiler from source code files, adds required code modules from program libraries supplied as part of C++, and welds everything into an executable whole.

The Libraries

Components of the System

ד''בס

11/9/2014 86

11/9/2014

DSP lab 34

ד''בס

11/9/2014 87

Solution

Explorer

window

Editor

window

Output

window

ד''בס

11/9/2014 88

11/9/2014

DSP lab 35

ד''בס

11/9/2014 89

ד''בס

11/9/2014 90

11/9/2014

DSP lab 36

ד''בס

11/9/2014 91

ד''בס

11/9/2014 92

Creating a project for a Win32

console application

11/9/2014

DSP lab 37

ד''בס

11/9/2014 93

Creating a project for a Win32

console application

ד''בס

11/9/2014 94

Creating a project for a Win32

console application

11/9/2014

DSP lab 38

ד''בס

11/9/2014 95

Class View

Property

Manager

Resource

View

ד''בס

11/9/2014 96

11/9/2014

DSP lab 39

ד''בס

11/9/2014 97

ד''בס

11/9/2014 98

11/9/2014

DSP lab 40

ד''בס

11/9/2014 99

ד''בס

11/9/2014 100

11/9/2014

DSP lab 41

ד''בס

11/9/2014 101

ד''בס

11/9/2014 102

Executing the Program

11/9/2014

DSP lab 42

ד''בס

11/9/2014 103

Creating an empty console project

ד''בס

11/9/2014 104

Creating an empty console project

11/9/2014

DSP lab 43

ד''בס

11/9/2014 105

ד''בס

11/9/2014 106

11/9/2014

DSP lab 44

ד''בס

11/9/2014 107

Creating an empty console project

ד''בס

11/9/2014 108

using namespace std;

11/9/2014

DSP lab 45

ד''בס

11/9/2014 109

ד''בס

11/9/2014 110

11/9/2014

DSP lab 46

ד''בס

11/9/2014 111

ד''בס

11/9/2014 112

11/9/2014

DSP lab 47

ד''בס

11/9/2014 113

ד''בס

11/9/2014 114

Creating an empty console project

11/9/2014

DSP lab 48

ד''בס

11/9/2014 115

Win32 Debug מול Win32 Release

מטרות שני עבור התוכנית את לבנות ניתן: Win32 Debug Target עבור או Win32 Release Target.

ה קובץ- EXE ה בגרסת- Debug המחיצה תחת ,הבניה לאחר ,ימצא ,DEBUG המחיצה תחת ,הבניה לאחר ,ימצא Release -ה בגרסת EXE -ה קובץ בעוד

RELEASE.

ה בגרסת-Release של אופטימיזציה ומתבצעת מאופשר לא השגיאות ניפוי לתהליך מיועדת Debug -ב גרסת .Debug -ה לגרסת בניגוד זאת ,המהירות

.המשתמש לידי למסירה מיועדת Release-ה גרסת בעוד עצמו הפיתוח

ה בגרסת תוכניות להגיש נא-Release הדואר דרך להעבירם יותר שקל מכיוון .הקטן נפחם בגלל האלקטרוני

ה בגרבת בחירה לשם-Release, ידי על המתאים הכלים סרגל את להוסיף יש:

Tools

Customize

Toolbars

Build

ד''בס

11/9/2014 116

http://www.ee.bgu.ac.il/~adcomplab/oop

C++ tutorials

11/9/2014

DSP lab 49

ד''בס

11/9/2014 117

ד''בס

Global Variables

If you want more than one function to share a

single copy of a variable, simply declare the variable

as global in all the functions. The global declaration

must occur before the variable is actually used in a

function.

Example:

function h = falling(t)

global GRAVITY

h = 1/2*GRAVITY*t.^2;

11/9/2014

DSP lab 50

ד''בס

Graphical User Interfaces GUIDE, the MATLAB Graphical User Interface

Development Environment, provides a set of tools

for creating graphical user interfaces (GUIs). These

tools greatly simplify the process of designing and

building GUIs. You can use the GUIDE tools to

perform the following tasks:

- Laying out the GUI.

ד''בס

- Programming the GUI.

Example template for a push button

11/9/2014

DSP lab 51

ד''בס

11/9/2014 121

The END