Sei sulla pagina 1di 16

Computer Programming

OOP and Function

Hung-Yu Wei
Department of Electrical Engineering
National Taiwan University

10/18/2006
Overview: function
 What is a function?
 A “black box” that does operations with
input values and then returns the output
value.
 Type_Out FunctionName (Type_In
InputVariable)
{
operations of the function;
}
function

Function_Name
return Y;
InputVariable

Type_In
Type_Out

Type_Out FunctionName (Type_In InputVariable)


{
operations of the function;
}
function

setCourseName void;

Name_X

String type

void setCourseName( string Name_X )


{
courseName = Name_X;
}
example: function

funcSquare
z
x
int int

int funcSquare( int x )


{
y is a local variable
int y;
y=x;
z=x*y;
return z;
}
Call a function from main
int main()
{
int output;
int input=3;
output=funcSquare(input);
return 0;

}
Object Oriented Programming
 OOP
 以物件為主的 programming
 Object
 物件
 白話翻譯: 1 個東西
 Class
 類別
 白話翻譯: 1 類東西

 How does object relate to class?


 object 是 class 的一個實體化 ( 特例 )
 狗 class
 可魯 object
What’s inside a class?
 Function ( 函式 )
 Data ( 資料 )
 i.e. variables( 變數 )

 What’s inside an object?


 Ans: same answer: function & data
 Remember:
Property of function and data
 access specifier
 can/cannot be accessed from outside
 2 types
 Public
 Private

 Tips: use private as often as possible


 Protect your data/function
class ( 類別 ) and object ( 物件 )
 Example
 class : 狗
 object: 小花,萊西,可魯
 Member function: 吠叫,吃,咬人,散步
 Data member :
 int age_ 年齡
 string breed_ 品種
 double weight_ 體重
class ( 類別 ) –UML notation
Name of a data member
Name of a class

1 data member
3 member functions

Name of a member function


+ public
- private
define a class
class dog()
{
public:
string breed_ 品種 ;
int age_ 年齡
void 吃 _function (string 食物名 稱 )
{ 消化食 物 }
double 散步 (string 路名 )
{ return 散步距 離 _ 公尺 ; }
void 吠叫 ()
{ cout <<“ 汪汪” ;}
};
create/use objects
int main()
{
dog 小花 , 可魯 ;
int x=3;
string lunch;
lunch=“an apple”;

可魯 .age_ 年齡 =x;
小花 .age_ 年齡 = 可魯 .age_ 年齡 +1;
可魯 . 吠叫 ;
cout << “Spot walks ” << 小花 . 散步 (“ 新生南路” ) << “meters
today”;
小花 . 吃 _function(lunch);
return 0;
}
More examples: class and object
 Define a class 長方形

class C_Rectangle {
int x, y; // 長,寬
public:
void set_values (int,int);
int area (void);
};
#include <iostream>
using std::cout;

class C_Rectangle {
public:
int x, y; Data member
void C_Rectangle::set_values (int a, int b) {
x = a;
y = b;
} Member function
int area(void) {
return (x*y);
}
};

int main () { 宣告物件


C_Rectangle my_1st_rect;
my_1st_rect.set_values (2,5); 呼叫函式
cout << "area size= " << my_1st_rect.area();
return 0;
}
Review questions
 What are the differences between
class and object?
 What are the differences between
data and function?
 What are the differences between
data member and member
function?

Potrebbero piacerti anche