Download - 2010 summer vacation

Transcript
Page 1: 2010 summer vacation

2010 summer vacation

Marshall, CEITL

Page 2: 2010 summer vacation

INDEX

• Struct• Dynamic memory allocation• Class• Constructor, destructor• template

2010 summer

Page 3: 2010 summer vacation

STRUCT

• Basic data types• Syntax• More…– Constructor– Destructor

• Homework

2010 summer

Page 4: 2010 summer vacation

Basic data types – types and sizesSTRUCT

Ref : http://msdn.microsoft.com/en-us/library/cc953fe1(v=VS.80).aspx

Category Type Size

Integral charunsigned charsigned char

1 byte

bool 1 byte

short / short intunsigned short

2 bytes

intunsigned int

4 bytes

long / long intunsigned long

4 bytes

float float 4 bytes

double 8 bytes

Page 5: 2010 summer vacation

Basic data types – range of valuesSTRUCT

Ref : http://msdn.microsoft.com/en-us/library/s3f49ktz(VS.80).aspx

Type name Bytes Range of values

Int 4 –2,147,483,648 ~ 2,147,483,647

Unsigned int 4 0 ~ 4,294,967,295

Bool 1 false / true

Char 1 –128 ~ 127

Unsigned char 1 0 ~ 255

Short 2 –32,768 ~ 32,767

Unsigned short 2 0 ~ 65,535

Long 4 –2,147,483,648 ~ 2,147,483,647

Unsigned long 4 0 ~ 4,294,967,295

float 4 3.4E +/- 38 (7 digits)

double 8 1.7E +/- 308 (15 digits)

Page 6: 2010 summer vacation

Exercise

• 有一長方體 a, 其長、寬、高為 (3,4,5) ;x,y,z 坐標分別為 (1,1,2), 沿 x, y, z 軸分別移動 (13,2,6) 後 , 中心坐標與其體積為 ?

• 有一長方體 b, 其長、寬、高為 (1,4,2) ;x,y,z 坐標分別為 (3,3,2), 沿 x, y, z 軸分別移動 (6,9,12) 後 , 中心坐標其體積為 ?

STRUCT

Page 7: 2010 summer vacation

STRUCTsyntax

struct PERSON{bool gender;int age;double height, weight;

};

void main(){PERSON tim;tim.gender = 1;tim.age = 18;tim.height= 180.0;tim.weight = 80.5;

//PERSON tim = {1,18,180.0,80.5};}

結構體的名字成員

分號宣告變數

存取成員

定義結構體

程示主體

也可以…

Page 8: 2010 summer vacation

Size of struct Size of

?

對於結構體,編譯器會自動進行成員變數的對齊,以提高運算效率。預設情況下,編譯器為結構體的每個成員按其自然對界( natural alignment )條件分配空間。自然對界是指按結構體的成員中 size最大的成員對齊。 第一個成員的位址和整個結構的位址相同。

STRUCT

Ref : http://stenlyho.blogspot.com/2007/04/ccstruct.html

struct PERSON{bool gender;int age;double height, weight;

};

Page 9: 2010 summer vacation

Constructor & destructor#include <iostream>#include <cstdlib>using namespace std;struct numbers{

int number1;double number2;numbers(){

number1 = 5;number2= 5.5;cout << "numbers is created! " << endl;

}~numbers(){

cout <<" 一個 number 的結構體被終結了 " << endl;}

};

void main(){cout << a.number1 << endl;cout << a.number2 << endl;

}

STRUCT

Ref :http://www.study-area.org/coobila/tutorial_422.html

建構函式

解構函式

Page 10: 2010 summer vacation

Constructor & destructor (2)#include <iostream>#include <cstdlib>using namespace std;

struct numbers{int number1;double number2;numbers(){

number1 = 5;number2= 5.5;cout << "numbers is created! " << endl;

}~numbers(){

cout <<“A numbers be terminated!" << endl;}

};void sub(numbers a){

cout << a.number1 << endl;cout << a.number2 << endl;

}

STRUCT

Ref :http://www.study-area.org/coobila/tutorial_422.html

void main(){cout << "main starts" << endl;numbers a;a.number1=100;a.number2=999;sub(a);sub(a);sub(a);sub(a);sub(a);cout << "main ended " << endl;

}

What will be output ?

Page 11: 2010 summer vacation

exercise

產生 10 個長方體 , 並以亂數產生其座標與長、寬、高。座標為小於 10 的整數,長寬高為小於 5 的浮點數。在結構體刪除時輸出”刪除了 (x,y,z)=(??,??,??),

(L,W,H)=(??,??,??) 的結構體”

Hint : rand() : 在 <cstdlib> 定義 , 隨機從 0~RAND_MAX 挑出一個整數。型別轉換 : (double)rand()/RAND_MAX

STRUCT

Page 12: 2010 summer vacation

SummarySize and range of data typesSyntax of structConstructor & destructor• What is ….• When will be called …..

Lifecycle of variablesStatic variablesAlignmentrand()

STRUCT

Page 13: 2010 summer vacation
Page 14: 2010 summer vacation

Dynamic memory allocation

• Data & memory address• Pointer & address• Array• Dynamic memory allocation• Exercise

2010 summer

Page 15: 2010 summer vacation

Data & memory addressvoid main(){

int i = 999;int* p = &i;

}

Dynamic memory allocation

Datatype … int …Name … i …Value … 999 …address 0048FC54 0048FC55 0048FC56 0048FC57 0048FC58 0048FC59

Datatype … Int* …Name … p …Value … 00 48 FC 55 …address 0031FD9F 0031FDA0 0031FDA1 0031FDA2 0031FDA3 0031FDA4

Page 16: 2010 summer vacation

Pointer & addressvoid main(){

int i = 999;int* p = &i; //int *p 或 int* p 均可// int* p1,p2,p3;// int *p1,*p2,*p3;

cout << i <<","<<&i << endl;cout << p << "," << *p << "," << & p << endl;

}

Dynamic memory allocation

Datatype Int Int* Int* int

Name i &I P *p

Value 999 0031FDAC 0031FDAC 999

adress 0031FDAC - 0031FDA0 0031FDAC( &*p )

int999

i

Int*0031FDAC

p0031FDAC

0031FDA0

Page 17: 2010 summer vacation

Array - syntax• 一維陣列 : int a[5] = {1,2,4,5,6};

– 取得可存放 5 個 int 的記憶體位置,並把起始位址存入 a– a[0] : 從 a 的位址走 0 步 , 取出一個 int– a[1] : 從 a 的位址走 1 步 , 取出一個 int

• 產生 10 個長方體 , 並以亂數產生其座標與長、寬、高。• 產生 200 個長方體 , 並以亂數產生其座標與長、寬、高。

Dynamic memory allocation

a[0] a[1] a[2] a[3] a[4]

Value … … … … …

address 0029FCF0 0029FCF4 0029FCF8 0029FCFC 0029FD00

Page 18: 2010 summer vacation

Array - syntax• 一維陣列 : int a[5] = {1,2,3,4,5};

• 二維陣列 : int b[3][2]={{1,2},{3,4},{5,6}};

Dynamic memory allocation

A[0] A[1] A[2] A[3] A[4]

Value … … … … …

address 0029FCF0 0029FCF4 0029FCF8 0029FCFC 0029FD00

B[0][0] B[0][1] B[1][0] B[1][1] B[2][0] B[2][1]

Page 19: 2010 summer vacation

Exercise• 以二維陣列與一維陣列計算下題結果 :

Dynamic memory allocation

????

22109

*

1154

6153

2231 • Hint :

int a[4][3];int b[3];int c[4];

Page 20: 2010 summer vacation

Dynamic memory allocation• 3 types of variables– Static– Normal– Dynamic

Void main(){ static int a[5];

int b[10];int* c = new int[10];

delete [] c;c= new int[200];

}

Dynamic memory allocation

Without “delete”, What will happen?

int Int Int Int Int Int Int Int Int int

Int*add

c

add

1

2

3

Page 21: 2010 summer vacation

2D dynamic matrix ( 3 x 2 )Dynamic memory allocation

Int int

Int int

Int int

Int* Int* Int*

Int**void main(){

int** a;a = new int*[3];for(int i = 0 ; I < 3 ; i++)a[i] = new int[2];

//a[0] = new int[2];//a[1] = new int[2];//a[2] = new int[2];

for(int i=0; i<3 ;i++){delete [] a[i];}delete [] a;

}

Page 22: 2010 summer vacation

Char arrayDynamic memory allocation

char c1 = ‘b’ ; char c[20] = “Hello!!” ;

char s[3][100] = {“Hello”, “world” , “!!”}

C[0] C[1] C[2] C[3] C[4] C[5] C[6] C[7] ~ c[19]

H E L L O ! ! \0

Page 23: 2010 summer vacation

Exercise

• 寫出一程式 , 讓使用者輸入整數 , 程式會將此整數因數分解 , 並存入兩整數陣列。分別存入 factor[] 與 power[].

Ex : 輸入 40 . 將存入 factor[] = {2,5}power [] = {3,1}即 40 = 23 * 51

Dynamic memory allocation

Page 24: 2010 summer vacation

SummaryDynamic memory allocation

Page 25: 2010 summer vacation
Page 26: 2010 summer vacation

Class

• Object oriented programming (OOP)• Member & method• Private & public• Constructor

2010 summer

Page 27: 2010 summer vacation

Exercise• 有一矩形 , 其長為 5, 寬為 3, 長邊方向與 Y 軸同向 , 另其與原點相距最遠的點為 corner1, 質量中心座標為 (3 , 7), 矩型對質量中心做

3 。 /sec 順時針轉動;且其中心對原點作 3 。 /sec 逆時針轉動 , 試求其第 0~180sec, corner1 的座標。

2010 summer

Y

X

corner1

Page 28: 2010 summer vacation

Object oriented programming (OOP)2010 summer

• 以物件為主的思考方式,能更直觀的將現實中的目標在程式中模擬出來。一般的想法 物件導向的想法

找出矩形中心點的位置

公轉角速度* 時間 * 半徑

自轉角速度* 時間 * 半徑

定義矩形:中心位置公轉路徑自轉方式長寬輸入時間

Corner1的坐標Corner1 的位置

Corner1 相對於中心點的位置

Page 29: 2010 summer vacation

Member & method2010 summer

class rectangular{private:

double xpos, ypos;double length, width;

public:rectangular(){

xpos = 0 ;ypos = 0 ;

}void setsize(double l, double w){

length = l;width = w;

}void move(double x , double y ){

xpos += x ;ypos += y;

}

void printcorner(){printf("corner1 : ( x , y ) =

( %f , %f)\n" , xpos + width/2 , ypos + length/2 );

printf("corner2 : ( x , y ) = ( %f , %f)\n" , xpos + width/2 , ypos - length/2 );

printf("corner3 : ( x , y ) = ( %f , %f)\n" , xpos - width/2 , ypos - length/2 );

printf("corner3 : ( x , y ) = ( %f , %f)\n" , xpos - width/2 , ypos + length/2 );}

}; 方法(method)

Page 30: 2010 summer vacation

Private & public2010 summer

• Encapsulation( 封裝性 ) : 透過存取權限設定而可達到資料保護的效果,• 權限的分類:– public : 不論物件內外均可存取。– Protect :     … skip…– Private : 物件內的成員才能存取。( C++ 預設)

• 通常,物件內的變數均會設成 private ,而方法設成 public ,要更改變數的內容均用呼叫 mehtod 來達成。

Page 31: 2010 summer vacation

Constructor definition & calling 2010 summer

class rectangular{private:

double xpos,ypos;double length, width;

public:rectangular(){

a = 0;}rectangular(double x, double y){

xpos =x ;ypos = y;

}rectangular(double x, double y, double l ,double w){

xpos = x;ypos= y;length = l;width = w;

}void setlocation(double x, double y){……}void setsize(double l, double w){……}void printcorner(){…….}

};

void main(){rectangular rectA; rectA.printcorner();rectA.setlocation(5.55,2.22);rectA.setsize(3.00, 5.00);rectA.printcorner();

rectangular rectB(123.33 ,22.1);rectB.printcorner();rectB.setsize(5.66 , 3.22);rectB.printcorner();

rectangular rectC(1 ,2, 3, 4);rectC.printcorner();

}

Constructors?

Page 32: 2010 summer vacation

Exercise• 一球由座標 (2000, 5000) 沿 x 軸方向發射,重力加速度 a(x,y) 為

(0, -9.8) ,請以 10 秒為單位 cout 出球的所在位置,至球落地為止。

• 有一矩形 , 其長為 5, 寬為 3, 長邊方向與 Y 軸同向,質量中心位置(x , y) = ( t , sin(x/360) ) , 矩型對質量中心做 3 。 /sec 順時針轉動;試求其第 0~180sec , 4 個角的座標。

2010 summer

Page 33: 2010 summer vacation

Class (2)• Pointer of class

– Syntax “->”– Special word “this”– Array of class

• More about constructor– Default constructor– Copy constructor– Normal constructor

• Operator overloading– Copy assignment operator– Operator overloading

2010 summer

Page 34: 2010 summer vacation

Pointer of class// 宣告類別的指標Class rect{Private:

double l,w,x,y;Public: rect(); void setsize(double l , double w); void setpos(double x, double y);

};

Void main(){rect *a = new rect; a->setsize(4,3);a->setpos(1,2);

}

class(2)

// 保留字 “ this” Class rect{Private:

double l,w,x,y;Public: rect(); void setsize(double l , double w){

this-> l = l;this->w = w;

} void setpos(double x, double y){

this-> x = x;this ->y = y;

}};

// 類別的陣列Class rect{Private:

double l,w,x,y;Public:

rect();setsize(double l , double w);setpos(double x, double y);

};

Void main(){rect r[3]; r[1].setsize(100,200);rect *a = new rect[3];a[0] .setsize(100,200);………

}

Page 35: 2010 summer vacation

Exercise

• 請將因式分解改寫為物件導向的版本。– 宣告一類別 number ,其中成員包含• 待因式分解的值 value ,• 結構體 factor ,內有 value 及 power ,均為

int[40]• 所以 value = factor.value[0]^factor.power[0]

*…..• 建構函式 number(int input) ,使得 input 為待分解值 value, 並在建構函式中完成分解。

Class(2)

Page 36: 2010 summer vacation

Constructor”s”

• Normal constructor• Default constructor• Copy constructor

Class(2)

Pan’s house Mar’s house

Page 37: 2010 summer vacation

Copy constructorclass house{private:

unsigned short door[3], wall[3]; unsigned short roof[3], chimney[3];

public:house(){} // default constructor

house(unsigned short *a,unsigned short *b, unsigned short *c,unsigned short *d ){

for(int i =0 ; i< 3 ; i++){this->door[i] = a[i] ;this->wall[i] = b[i] ;this->roof[i] = c[i] ;this->chimney[i] = d[i] ;

}} //normal constructor

Class(2)

void main(){

unsigned short color1[3] ={255,255,255} ; unsigned short color2[3] ={255,255,0};unsigned short color3[3] ={0,255,0};unsigned short color4[3] ={255, 0 ,0};

house pan(color1 , color2, color3 ,color4);house mar(pan);

}

house(const house& other){for(int i =0 ; i< 3 ; i++){

this->door[i] = other.door[i] ;this->wall[i] = other.wall[i] ;this->roof[i] = other.roof[i] ;this->chimney[i] =

other.chimney[i] ;}

} //copy constructor};

Page 38: 2010 summer vacation

Operator overloading

//copy values between variablesint a = 5; int b;b=a;

//copy values between classeshouse pan(color1,color2,color3,color4);house mar; mar = pan //?????????

Class(2)

可以執行 , 但會有問題 ,尤其是指標成員

初始化 /Initialize指定 /assign

Page 39: 2010 summer vacation

Operator overloading//Copy assignment operator

class house(){…house& operator=(const house& other){this->~house();for(int i =0 ; i< 3 ; i++){this->door[i] = other.door[i] ;this->wall[i] = other.wall[i] ;this->roof[i] = other.roof[i] ;this->chimney[i] = other.chimney[i] ;}return *this;}…

};

Class(2)

常數變數 (const variable) :只能在初始化改變其值 ,之後即無法更改的變數

a=(b=c);

Page 40: 2010 summer vacation

Operator overloading

//other operatorsclassX operator+(const classX& rightObj){

classX ans ;ans.data1 = data1+rightObj.data1;..............return ans;

}

Class(2)

Page 41: 2010 summer vacation

Exercise完成下面類別 :

Class intarray{Private:

int* value; // 值的陣列int size; // 值陣列的大小

Public:intarray();intarray(int* input, int size); //intarray(const intarray& other);~intarray();

void setvalue(int * input, int size); // 設值的 functionintarray& operator=(const intarray& other); //copy assignment operatorintarray operator+(const intarray& other); // 將兩個陣列接起來

};

Class(2)

Page 42: 2010 summer vacation
Page 43: 2010 summer vacation

template

• What template can do• Function template• Class template• Non-Type Parameter

2010 summer

Page 44: 2010 summer vacation

What template can do

int myAdd(int a, int b){return a+b;

}

template

double myAdd(double a, double b){return a+b;

}

Template <class T>T myAdd(T a,T b){

return a+b;}

unsigned short

float ????

Page 45: 2010 summer vacation

Syntaxtemplate

template<class T>void functionX(…){

…T data;…

}

template<typename T>class Y{

…T data;…

};

template<class T1, class T2>class Z{

…T1 data;T2 data1;…

};

• Function of compiler• Key word “class”/”typename”• Can apply to either class or function• Multi type paraments are acceptable

Page 46: 2010 summer vacation

Function templatetemplate

#include <iostream>

using namespace std;

int myAdd(int a ,int b){cout << "processing int myAdd" << endl;return a+b;

}

template<class T>T myAdd(T a, T b){

cout << "processing template myAdd" << endl;return a+b;

}

void main(){double a=1, b=2 ;

cout << myAdd(a,b) << endl; }

Page 47: 2010 summer vacation

class templatetemplate

template<class T1, class T2>class myClass{private:

T1* a;T2* b;

public:myClass(){

a= new T1[0];b= new T2[0];cout << "template class in created ... " <<

endl;}

};

void main(){myClass<int,int> c1,c2;

}

template<class T1, class T2>class myClass;

原型宣告實現

呼叫

Page 48: 2010 summer vacation

Non-Type Parametertemplate

#include <iostream>

using namespace std;

template<class T, int i>class Buffer{

T v[i];int size;

public://Buffer():size(i) {} Buffer(){ size = i; }void print(){

cout << "size=" << size <<"," << v << endl;}

};

void main(){Buffer<char , 127> cBuf ; cBuf.print();

Page 49: 2010 summer vacation

Default values Parametertemplate

#include <iostream>

using namespace std;

template<class T = string , int i=127>class Buffer{

T v[i];int size;

public://Buffer():size(i) {} Buffer(){ size = i; }void print(){

cout << "size=" << size <<"," << v << endl;}

};

void main(){Buffer<char > cBuf ; cBuf.print();

Page 50: 2010 summer vacation

Template specializationtemplate

template<class T>class List; // 當其定義無法適用於所有的型態時 , 無法適用的型態要另// 外定義template<>class List<char*>;// 定義當宣告為 char* 時 , class List 的成員內容

Page 51: 2010 summer vacation

Exercise• 定義一個點物件 class point, • 內部成員為點位置 , 點位置以陣列方式儲存 pos[], • 考慮到點可能為 1 維 ,2 維 ,3 維或更高 , 故以 template 的方式來對不同維度的點物件來做生成 . • 並在物件內定義計算距離的函式

– double distance(point& other),– ( 只有同樣維度的點物件可計算距離 ) 。

• 物件內定義輸出函式– point::print();

template

Page 52: 2010 summer vacation

Exercise - answertemplate

template<int d>class point{private:

double pos[d];public:

point(){for(int i = 0 ; i<d ; i++) pos[i] = 0;

}point(double* input){

for(int i = 0 ; i < d ; i++) pos[i] = input[i];}double distance(const point<d>& other){

double tmp = 0;for(int i = 0 ; i < d ; i++){ tmp += (this->pos[i] - other.pos[i]) * (this->pos[i] - other.pos[i]);}return sqrt(tmp);

}void print(){

cout << "(" ; for(int i =0 ; i <d ; i++) cout << " "<<pos[i] <<" " ; cout << ")";

}};

// 對一維的處理特殊化template<>double point<1>::distance(const point<1>& other){

return abs(this->pos[0] - other.pos[0] ); }

Page 53: 2010 summer vacation

Exercise - answertemplate

template<class T, int d>class point{private:

T pos[d];public:

point(){for(int i = 0 ; i<d ; i++) pos[i] = 0;

}point(T* input){

for(int i = 0 ; i < d ; i++) pos[i] = input[i];}double distance(const point<T, d>& other){

T tmp = 0;for(int i = 0 ; i < d ; i++){ tmp += (this->pos[i] - other.pos[i]) * (this->pos[i] - other.pos[i]);}return sqrt( (double)tmp );

}void print(){

cout << "(" ; for(int i =0 ; i <d ; i++) cout << " "<<pos[i] <<" " ; cout << ")";

}};

// 對一維的處理特殊化無法對單一 type 做特殊化……=> 無法只對 d 做特殊化……

Page 54: 2010 summer vacation

HOMEWORK• 定義一物件 type_arr,

– 成員為變數陣列與陣列長度 , 陣列型態以 template 定義 , – 定義一成員函式 , type_arr add(conts typearr& other), 內容為將兩物件內陣列值一對一相加 – 在陣列 type 為 char 時 , 為 type_arr add(conts typearr& other) 定義一特殊化成員函式 , 內容為將第二個 type_arr 之陣列附加在第一個 type_arr 陣列之後

• EX : – Add( (3,3,5) , (1,2,3,5) ) => (4,5,8,5)– Add( (Yes!) , ( take a break!!) ) = ( Yes! take a break!! )

template