Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore หลักการเขียนโปรแกรม ปวส.

หลักการเขียนโปรแกรม ปวส.

Published by tamcomed50, 2020-12-27 06:22:21

Description: หลักการเขียนโปรแกรม ปวส.

Search

Read the Text Version

! 149 void Date:: Display() //เมมเบอรฟง กชนั ของคลาส Date { สรา ง member function ชื่อ Display() สเตตเมนตใ นฟง กช นั ; เปนสมาชิกของคลาส Date โดยกําหนด สเตตเมนตใ นฟง กช นั ; ดว ยเครอ่ื งหมาย :: } void main() { สเตตเมนตใ นโปรแกรม; สเตตเมนตใ นโปรแกรม; } รปู แบบท่ี 3 กาํ หนดรายละเอียดของเมมเบอรฟงกชันอยูภายในคลาส ไมตองเขียนชื่อ คลาส และไมตองเขยี นเครอื่ งหมายแบง แยกขอบเขต :: (scope resolution operator) นาํ หนา ชือ่ เมมเบอรฟ ง กช นั เหมาะสาํ หรบั โปรแกรมทม่ี เี มมเบอรฟ ง กช นั จํานวนไมมาก และมีรายละเอียดของ ฟงกชันสั้น ๆ มรี ปู แบบดงั น้ี class Date { private: // use only in this class int Year; //ดาตา เมมเบอร int Month; //ดาตา เมมเบอร int Day; //ดาตา เมมเบอร public: //use internal and external of this class void SetDate(int Y, int M, int D); //เมมเบอรฟ ง กช ันของคลาส Date { สรา ง member function ชอ่ื SetDate() สเตตเมนตใ นฟง กช นั ; เปน สมาชกิ ของคลาส Date โดยสรา งไว } ในคลาส void Display() //เมมเบอรฟ ง กช นั ของคลาส Date { สรา ง member function ชอ่ื Display() สเตตเมนตใ นฟง กช นั ; เปน สมาชิกของคลาส Date โดยสรา งไว } ในคลาส }; ! ศิริชยั นามบุรี การเขียนโปรแกรมแบบ OOP

! 150 v{oid main() } สเตตเมนตใ นโปรแกรม; หมายเหตุ การสรา งคลาสและรายละเอยี ดของเมมเบอรฟ ง กช นั อาจใชหลายรูปแบบรวมกันได ♦!การสรา งและเรยี กใชอ อบจก็ ตจ ากคลาส กอนที่จะสรางออบเจ็กตใชในโปรแกรมไดจะตองสรางคลาสใหถูกตองกอนเพราะ คลาส(class) เปน ตน กําหนดของออบเจ็กต ซึ่งภายในคลาสจะตองกาํ หนด ดาตา เมมเบอรแ ละเมมเบอรฟ ง กช นั ไว และจะตองเขียน code ของเมมเบอรฟ ง กช นั ใหเ สรจ็ สมบรู ณก อ น จึงจะสามารถนาํ ชื่อคลาสไปสราง ออบเจก็ ตแ ละเรยี กใชอ อกเจก็ ตไ ด •! ตัวอยางโปรแกรม clas_ex1.cpp เปนตัวอยางการสรางคลาส การสรางออบเจ็กตและการ เรียกใชออบเจ็กตเบื้องตน โดยสรางเมมเบอรฟงกชันไวตอจากฟงกชัน main() ดังนี้ /*Program : clas_ex1.cpp Process : simple example of class*/ #include <iostream.h> #include <conio.h> class Date //create class Date { private: int Year; //data member int Month; //data member int Day; //data member public: void SetDate(int Y, int M, int D); //member function void Display(); //member function }; void main() //begin main program { Date birthday; //สรางออบเจ็กตชื่อ birthday จากคลาสชื่อ Date clrscr(); cout<<\"Display First OOP Programming\"<<endl; birthday.SetDate(2540,12,25); //เรยี กใชอ อปเจก็ ต birthday และฟงกชั่น SetDate() ทาํ งาน birthday.Display(); //เรยี กใชอ อปเจก็ ต birthday และฟงกชัน display() ทาํ งาน getch(); } //end main program ! ศิริชัย นามบุรี การเขียนโปรแกรมแบบ OOP

! 151 void Date::SetDate(int Y, int M, int D) //detail of member function { Year = Y; Month = M; Day = D; } void Date::Display() //detail of member function { cout<<\"Year : \"<<Year<<endl; cout<<\"Month: \"<<Month<<endl; cout<<\"Date : \"<<Day<<endl; } จากโปรแกรมตวั อยา ง สรุปไดสวนสําคญั ได ดงั น้ี 1. การสรา งคลาสหรอื กําหนดคลาสไมใชการสรางออบเจ็กต เปนเพยี งแตแ สดงใหท ราบวา เมอ่ื มกี ารสรา งออบเจก็ ตแ ลว ออบเจก็ ตท ไี่ ดจ ะมีสว นประกอบเหมอื นทม่ี อี ยใู นคลาส ซง่ึ ในโปรแกรมได สรา งออบเจก็ ตข น้ึ 1 ออบเจก็ ตช อ่ื วา birthday จากประโยค Date birthday; แสดงวา birthday เปน ออบเจก็ ตท ม่ี สี ว นประกอบเหมอื นทม่ี อี ยใู นคลาส Date 2. การเรยี กใชเ มมเบอรฟ ง กช นั ของออบเจก็ ต ตอ งเขยี นสเตตเมนตใ หถ กู ตอ ง คอื มี สวนประกอบ 3 สวนคือ ชื่อออบเจ็กต. ชื่อเมมเบอรฟงกชัน() พรอ ม argument ของฟงกชัน(ถามี) เชน ออบเจก็ ต ฟงกชัน birthday.SetDate(2540,12,25); อารกิวเมนตของฟงกชัน ออบเจก็ ต birthday.Display(); ฟงกชัน เครอ่ื งหมาย . มชี อ่ื เรยี กวา คลาสเมมเบอรแ อคเซสโอเปอเรเตอร (class member access operator) เปน โอเปอเรเตอรเ พอ่ื เรยี กใชส มาชกิ ของคลาส ! ศิริชัย นามบุรี การเขียนโปรแกรมแบบ OOP

! 152 •! ตัวอยางโปรแกรม clas_ex2.cpp แสดงถงึ การกาํ หนดใหดาตาเมมเบอรและเมมเบอร ฟง กช นั เปน ลกั ษณะ public ดังนั้นการเรียกใชออบเจ็กต birthday ในฟงกชัน main() จึง สามารถเรียกใชดาตาเมมเบอรของ class ไดดวย จึงสามารถกาํ หนดคาคงที่ให Year, Month, Day ไดโดยตรง ดังรายละเอียดโปรแกรมตอไปนี้ /*Program : clas_ex2.cpp Process : using public member of class*/ #include <iostream.h> #include <conio.h> class Date //create class Date { public: //use internal and external class int Year; //data member int Month; //data member int Day; //data member void SetDate(int Y, int M, int D); //member function void Display(); //member function }; void main() //begin main program { Date birthday; //create object name …birthday clrscr(); //set value to data member of class from object birthday.Year=2540; birthday.Month=12; birthday.Day = 25; cout<<\"Display Second OOP Programming\"<<endl; birthday.Display(); getch(); } //end main program void Date::SetDate(int Y, int M, int D) //detail of member function { Year = Y; Month = M; Day = D; } void Date::Display() //detail of member function { cout<<\"Year : \"<<Year<<endl; cout<<\"Month: \"<<Month<<endl; cout<<\"Date : \"<<Day<<endl; } ! ศิริชยั นามบุรี การเขียนโปรแกรมแบบ OOP

! 153 •! โปรแกรม oop_exam.cpp แสดงการสรางคลาสที่ชื่อวา VarClass ภายในคลาสประกอบไป ดวย ดาตาเมมเบอร CharVar, IntVar, FloatVar และมีเมมเบอรฟงกชันชื่อ SetValue และ DisplayData โดยเขียนไวภายในคลาส จากนั้นไดสรางออบเจ็กตชื่อ Obj_number ดังตอไปนี้ /*Program : oop_exam.cpp Process : Create New Class and Object*/ #include <iostream.h> #include <conio.h> class VarClass //Begin create class name is... VarClass { private: //data member char CharVar; int IntVar; float FloatVar; public: //member function void SetValue() //function in class { CharVar = 'A'; IntVar = 100; FloatVar= 3.14159; } void DisplayData() //function in class { cout<<\"Character : \"<<CharVar<<endl; cout<<\"Integer : \"<<IntVar<<endl; cout<<\"Float : \"<<FloatVar<<endl; } }; //end of class void main() //begin main program { VarClass Obj_number; //create object name is Obj_number clrscr(); Obj_number.SetValue(); Obj_number.DisplayData(); getch(); } // end main program ! ศิริชัย นามบุรี การเขียนโปรแกรมแบบ OOP

! 154 •! ตัวอยางโปรแกรม oop_exa2.cpp มผี ลการทํางานเหมอื นโปรแกรม oop_exam.cpp แต เขยี นเมมเบอรฟ งกช ันไวนอกคลาส และสรางไวหลังฟงกชัน main() มรี ปู แบบดงั น้ี /*Program : oop_exam.cpp Process : Create New Class and Object*/ #include <iostream.h> #include <conio.h> class VarClass //Begin create class name is... VarClass { private: //data member char CharVar; int IntVar; float FloatVar; public: void SetValue(); //member function void DisplayData(); //member function }; //end of class void main() //begin main program { VarClass Obj_number; //create object clrscr(); Obj_number.SetValue(); //call object and function Obj_number.DisplayData(); //call object and function getch(); } void VarClass::SetValue() //function in class { CharVar = 'A'; IntVar = 100; FloatVar= 3.14159; } void VarClass::DisplayData() //function in class { cout<<\"Character : \"<<CharVar<<endl; cout<<\"Integer : \"<<IntVar<<endl; cout<<\"Float : \"<<FloatVar<<endl; } ! ศิริชยั นามบุรี การเขียนโปรแกรมแบบ OOP

! 155 •! ตัวอยางโปรแกรม clas_ex3.cpp มกี ารสรา งเมมเบอรฟ ง กช นั GetDate() เพิ่มใน โปรแกรมเพอ่ื ทําหนา ทร่ี บั คา คงทท่ี างคยี บ อรด และสรางออบเจ็กตชื่อ Dday เพ่ิมขน้ึ อกี หนึ่งออบเจ็กต ดังนี้ /*Program : clas_ex3.cpp Process : using public member of class */ #include <iostream.h> #include <conio.h> class Date //create class Date { public: //use internal and external class int Year; //data member int Month; //data member int Day; //data member void GetDate(); //member function ...enter date void SetDate(int Y, int M, int D); //member function...send argumen void Display(); //member function...display date }; void main() //begin main program { Date birthday,Dday; //create 2 objects from Date class are birthday and Dday clrscr(); //set value to data member of class birthday.GetDate(); cout<<\"Display Date enter from keyboard by object :birthday\"<<endl; birthday.Display(); getch();clrscr(); cout<<endl<<\"Display Date from argument by object : Dday\"<<endl; Dday.SetDate(2530,11,29); Dday.Display(); getch(); } //end main program void Date::GetDate() //detail of member function GetDate() { cout<<\"Enter new Year<yyyy>: \";cin>>Year; cout<<\"Enter new Month<mm>: \";cin>>Month; cout<<\"Enter new Day<dd>: \";cin>>Day; } ! ศิริชัย นามบุรี การเขียนโปรแกรมแบบ OOP

! 156 void Date::SetDate(int Y, int M, int D) //detail of member function SetDate() { Year = Y; Month = M; Day = D; } void Date::Display() //detail of member function display() { cout<<\"Year : \"<<Year<<endl; cout<<\"Month: \"<<Month<<endl; cout<<\"Date : \"<<Day<<endl; } •! โปรแกรม oop_ex1.cpp แสดงการสรา งคลาสชอ่ื Calculate กําหนดใหมีสมาชิกเปน data member ลกั ษณะ private จาํ นวน 2 ตัว คือ first และ second กําหนดใหม ี member function จาํ นวน 4 ฟงกชัน คือ sum(), subtract(), multiply(), divide() เพอ่ื ทําหนาที่ในการ คาํ นวณการบวก,ลบ,คูณและหาร ของเลข 2 จาํ นวนตามลาํ ดับ ในโปรแกรมมกี ารสรา ง object จาํ นวน 1 objcect ชื่อ math แลว นําออบเจก็ ตน ม้ี าเรยี กใชใ นโปรแกรม ดังตอไปนี้ /*Program : oop_exp1.cpp Process : calculate */ #include <iostream.h> #include <conio.h> class Calculate //create class { private: float first; float second; public: float sum(float x, float y); float subtract(float a, float b); float multiply(float a, float b); float divide(float a, float b); }; //declaration prototype void input(); //Not member function //declar global variable float number1,number2; Calculate math; //create object ....math from Calculate class ! ศิริชัย นามบุรี การเขียนโปรแกรมแบบ OOP

! 157 void main() //begin main program { input(); cout<<\"\\nResult of sum = \"<<math.sum(number1,number2); cout<<\"\\nResult of subtract = \"<<math.subtract(number1,number2); cout<<\"\\nResult of multiply = \"<<math.multiply(number1,number2); cout<<\"\\nResult of devide = \"<<math.divide(number1,number2); getch(); } //end main program void input() // Normal function enter 2 number , non member of class { clrscr(); cout<< \"input first number : \";cin>>number1; cout<< \"input first number : \";cin>>number2; } //member function sum() of class Calculate float Calculate::sum(float first, float second) { return first+second; } //member function subtract() of class Calculate float Calculate::subtract(float first, float second) { return first-second; } //member function multiply() of class Calculate float Calculate::multiply(float first, float second) { return first*second; } //member function divide() of class Calculate float Calculate::divide(float first, float second) { return first/second; } ! ศิริชัย นามบุรี การเขียนโปรแกรมแบบ OOP

! 158 •! ตัวอยางโปรแกรม oop_ex2.cpp แสดงการคํานวณการตดั เกรด โดยการสรางคลาสชื่อ Grade และสรางออบเจ็กตชื่อ Evalue มกี ระบวนการทํางานของ member function อยู 3 ฟงกชัน คือ GetScore() ทาํ หนาที่รับคะแนนระหวางภาคและปลายภาค รวมคะแนน, Calculate() ทาํ หนาที่นาํ คะแนนรวมไปคาํ นวณตัดเกรด และ Display() ทาํ หนาที่แสดงผล คะแนนรวมและเกรดที่ไดรบั ดังรายละเอียดในโปรแกรมตอไปนี้ /*Program: grade2.cpp Process: calculate grade from total score by OOP Programming*/ #include <iostream.h> #include <conio.h> class Grade //create class ...Grade { private: float midterm; //data member float final; float total; char gd; public: void GetScore(); //member function void Calculate(); void Display(); }; Grade Evalue; //Create object ....Evalue void main() //begin main program { clrscr(); cout<< \"Program Calculate Grade\"<<endl; //use object and function of class Evalue.GetScore(); Evalue.Calculate(); Evalue.Display(); getch(); } void Grade::GetScore() //member function of Grade class { cout<< \"Enter midterm score: \";cin>>midterm; cout<< \"Enter midterm score: \";cin>>final; total=midterm+final; } ! ศิริชยั นามบุรี การเขียนโปรแกรมแบบ OOP

! 159 void Grade::Calculate() //member function of Grade class { //calculate grade use if...else if.. if (total<0 || total>100) //check enter error score gd = '*'; else if (total>=0 && total<=49) gd='F'; else if(total>=50 && total<=59) gd='D'; else if(total>=60 && total<=69) gd='C'; else if(total>=70 && total<=79) gd='B'; else gd='A'; } void Grade::Display() //member function of Grade class { cout<< \"Total of your score: \\a\"<<total<<endl; cout<< \"You get grade : \"<<gd<<endl; if (gd=='*') cout<< \"Your score = \"<<total<< \" is error range !!!\"<<endl; } •! ตัวอยางโปรแกรม exp_oop1.cpp แสดงการเขยี นโปรแกรมแบบ OOP โดยมเี มมเบอร ฟงกชัน 2 ฟงกชัน คือ input() และ display() โดยทฟ่ี ง กช นั input() ทาํ หนา ทร่ี บั ขอ มลู ทาง แปนพิมพ และฟงกชัน display() ทําหนา ทแ่ี สดงผลขอ มลู ทก่ี รอกทางแปน พมิ พไ ว /*Program: EXP_OOP1.CPP Process: Input,Display data function*/ #include <iostream.h> #include <conio.h> #include <stdio.h> class TEST //create class { public: char name[30]; //data member char address[50]; int age; public: //member function void input(); void display(); }; ! ศิริชยั นามบุรี การเขียนโปรแกรมแบบ OOP

! 160 TEST Info; //create object ...Info... from class void main() //begin main program { clrscr(); Info.input(); Info.display(); } void TEST::input() //Create member function of class TEST { cout<<\"Enter your information: \"<<endl; cout<<\"Name: \"; gets(name); cout<<\"Address: \"; gets(address); cout<<\"Age: \"; cin>>age; } void TEST::display() //Create member function of class TEST { clrscr(); cout<<\"*********************\"<<endl; cout<<\"Your information... \"<<endl; cout<<\"*********************\"<<endl; cout<<\"Name: \"<<name<<endl; cout<<\"Address: \"<<address<<endl; cout<<\"Age: \"<<age <<endl; cout<<\"*********************\\a\\a\"<<endl; getch(); } •! ตัวอยางโปรแกรม Draw_cir.cpp เปน โปรแกรมสรา งออบเจก็ ต ชื่อ TheCircle จากคลาส Circle โดยกําหนดเมมเบอรฟงกชันเพื่อกาํ หนดตาํ แหนง วาดวงกลมโดยการกําหนดคา SetCircle() และรับคาตําแหนง ของวงกลม InputCircle() พรอมแสดงผลการวาดวงกลม Display() ดังตอไปนี้ /*Program : Draw_cir.cpp Process : set position and draw circle graphics by OOP */ #include <iostream.h> #include <stdlib.h> #include <graphics.h> ! ศิริชัย นามบุรี การเขียนโปรแกรมแบบ OOP

! 161 การเขียนโปรแกรมแบบ OOP #include <conio.h> class Circle { private: int X, Y, Radius; public: void SetCircle(int,int,int); void InputCircle(); void Display(); }; void main() { Circle TheCircle; //create object ....TheCircle clrscr(); /* request auto detection */ int gdriver = DETECT, gmode, errorcode; /* initialize graphics mode */ initgraph(&gdriver, &gmode, \"\"); TheCircle.SetCircle(300,200,200); //set X,Y and Radius TheCircle.Display(); //Display Circle TheCircle.SetCircle(300,200,100); //set X,Y and Radius TheCircle.Display(); //Display Circle getch();clrscr(); TheCircle.InputCircle(); //Enter X,Y and Radius TheCircle.Display(); //Display Circle getch(); closegraph; } void Circle::SetCircle(int Xc, int Yc, int Rc) { X=Xc; Y=Yc; Radius=Rc; } void Circle::Display() { circle(X,Y,Radius); } ! ศิริชัย นามบุรี

! 162 void Circle::InputCircle() { closegraph; cout<< \"Enter data for circle:\"<<endl; cout<< \"Center point : X = \";cin>>X; cout<< \"Center point : Y = \";cin>>Y; cout<< \"Radius : \";cin>>Radius; } ♦ต! วั อยา งการเขยี นโปรแกรมแบบ OOP จดั การ Array และ Structure เราสามารถจดั การขอมลู ท่เี ปน array โดยสรางใหเปนขอมลู ชนิด Object ได ดงั ตวั อยา ง โปรแกรมตอ ไปน้ี ตัวอยางโปรแกรม OOP_ARR.CPP แสดงการใช array ทีเ่ ปน Object ชื่อ Object คือ result [5] สรางจาก class ที่ชื่อ TEST โดยจอง array ไวทั้งหมด 5 ชอ ง มี member function ของ class คือ input(), summation(), display() โ ดยที่ฟงกชัน input() ทาํ หนาที่รับขอมูลเขาไปเก็บใน data ที่ชื่อ number1, number2 ฟงกชัน summation() ทาํ หนา ทรี วมจํานวน number1+number2 เก็บไวใน sum และฟงกชัน display() ทาํ หนาที่แสดงขอมูล array ใน data ที่ชื่อ number1, number2 ที่ไดกรอกไว 5 จํานวน /*Program: OOP_ARR.CPP Process: Uses array of Object for Input,Summation,Display data function*/ #include <iostream.h> #include <conio.h> #include <stdio.h> class TEST //create class { public: //data members int number1; int number2; int sum; public: //member function void input(); void display(); void summation(); }; ! ศิริชัย นามบุรี การเขียนโปรแกรมแบบ OOP

! 163 การเขียนโปรแกรมแบบ OOP TEST result[5]; //Create Object ....is Array result[5] void main() { clrscr(); for(int i=0;i<=4;i++) { result[i].input(); } cout<<endl<<\"Display number 1, number 2 in array\"<<endl; for(i=0;i<=4;i++) { result[i].display(); } //Calculate Summation number1+number2 in array for(i=0;i<=4;i++) { result[i].summation(); } getch(); cout<<endl<<\"Display Summation: \"<<endl; for(i=0;i<=4;i++) { cout<<\"Sum[\"<<i<<\"]\"<<result[i].sum<<endl; } getch(); } //end main program void TEST::input() //Create member function of class TEST { cout<<\"Enter your number: \"<<endl; cout<<\"Number1: \";cin>>number1; cout<<\"Number2: \";cin>>number2; } void TEST::display() //Create member function of class TEST { cout<<\"Your number : \"<<endl; cout<<\"Number1: \"<<number1<<endl; cout<<\"Number2: \"<<number2<<endl<<endl; } ! ศิริชยั นามบุรี

! 164 void TEST::summation() { sum=number1+number2; } •! ตัวอยางโปรแกรม OOP_STRU.CPP เปน ตวั อยา งโปรแกรมเขยี นแบบ OOP เพื่อจัดการ ขอ มลู ทเ่ี ปน อารเ รยข องโครงสรา ง มีดังตอไปนี้ /*Program: OOP_STRU.CPP Process: Used OOP manage Array of Structure */ #include <iostream.h> #include <conio.h> #include <stdio.h> //for gets() function struct PER //Create Structure Data Type ....Global { char code[5]; char name[30]; char position[20]; float salary; }; class EMP //Create Class for origin of Object { public: PER person[5]; //data member is ...array of PER public: void Input(); //member function void Display(); void Report(); }; EMP Employee; //Creat Object from class ...EMP void main() { clrscr(); Employee.Input(); Employee.Display(); getch();clrscr(); ! ศิริชยั นามบุรี การเขียนโปรแกรมแบบ OOP

! 165 Employee.Report(); getch(); } void EMP::Input() //Detail of member function { int i; for(i=0;i<=4;i++) { cout<<\"Code: \";gets(person[i].code); cout<<\"Name: \";gets(person[i].name); cout<<\"Position: \";gets(person[i].position); cout<<\"Salary: \";cin>>person[i].salary; } } void EMP::Display() //Detail of member function { int i; clrscr();cout<<\"Display Information\"<<endl; for(i=0;i<=4;i++) { cout<<\"Record#\"<<i+1<<endl; cout<<person[i].code<<endl; cout<<person[i].name<<endl; cout<<person[i].position<<endl; cout<<person[i].salary<<endl; getch();clrscr(); } } void EMP::Report() //Detail of member function { int r=6,i; clrscr(); gotoxy(25,1);cout<<\"Report Salary Expense\"; gotoxy(25,2);cout<<\"Sirichai Export Co.ltd\"; gotoxy(1,3);cout<<\"----------------------------------------------------\"; gotoxy(1,4);cout<<\"Code Name - Surname Position Salary\"; gotoxy(1,5);cout<<\"----------------------------------------------------\"; for(i=0;i<=4;i++) { gotoxy(1,r);cout<<person[i].code; gotoxy(8,r);cout<<person[i].name; gotoxy(25,r);cout<<person[i].position; gotoxy(40,r);cout<<person[i].salary; ! ศิริชัย นามบุรี การเขียนโปรแกรมแบบ OOP

! 166 r++; if(r>=22) { getch(); r=6; } } } ♦!ฟง กช นั ชนดิ คอนสตรกั เตอรแ ละดสิ ตรกั เตอร จากตัวอยางที่ผานมาในการกาํ หนดคาใหแกดาตาเมมเบอรของคลาสในขณะเรียกใช ออปเจก็ ตน น้ั เราจะกาํ หนดคาคงที่ใหขณะที่มีการเรียกใช เชน Dday.SetDate(2530,11,29); หรอื มกี ารรบั คา ทางคยี บ อรด เพอ่ื กาํ หนดคา ดาตาเมมเบอร การกาํ หนดคาใหแกดาตาเมมเบอรสามารถกาํ หนดใหม คี า เรม่ิ ตน แบบอตั โนมตั ไิ ด โดยการใช เมมเบอรฟ ง กช นั ชนดิ ทเ่ี รยี กวา คอนสตรักเตอร (constructor) ซึ่งจะเปนเมมเบอรฟงกชันที่ทาํ งานโดย อั ต โ น มั ติ ทั น ที ที่ อ อ บ เ จ็ ก ต  ถู ก ส ร  า ง ข้ึ น เ พ ร า ะ ฉ ะ น้ั น จ ะ ต  อ ง กํ า ห น ด ค  า เ ร่ิ ม ต  น ข อ ง ดาตาเมมเบอรไ วเ ปน คา เรม่ิ ตน ดว ย การสรา งเมมเบอรฟ ง กช นั ชนดิ คอนสตรกั เตอร สรางไวใน class กาํ หนดชอ่ื ใหเ หมอื นกบั ชอ่ื ของ class และกาํ หนดคาคงที่ใหแก ดาตาเมมเบอรภ ายในเครอ่ื งหมาย { } ดงั รปู แบบตวั อยา งในโปรแกรม cons_oop.cpp •! ตัวอยางโปรแกรม cons_oop.cpp แสดงการสรา ง constructor เพื่อกําหนดคาเริ่มตน อัตโนมัติเมื่อมีการใชออปเจ็กต มีรายละเอียดดังนี้ /*Program : cons_oop.cpp Process : create constructor member function of class*/ #include <iostream.h> #include <conio.h> class Date //create class Date { private: int Year; //data member int Month; //data member int Day; //data member public: Date() //constructor member function…function name same as class name { Year = 1997; //คาคงที่ของ data member ที่เปนคาเริ่มตน Month=12; Day=31; } ! ศิริชยั นามบุรี การเขียนโปรแกรมแบบ OOP

! 167 void SetDate(int Y, int M, int D); //member function void Display(); //member function }; void main() //begin main program { Date birthday; clrscr(); cout<<\"Display Constructor member function : OOP Programming\"<<endl; //use constructor cout<<endl<<\"Display Date from constructor member function\"<<endl; birthday.Display(); //set value of data member cout<<endl<<\"Display Date from setting value\"<<endl; birthday.SetDate(2540,10,22); birthday.Display(); getch(); } //end main program void Date::SetDate(int Y, int M, int D) //detail of member function { Year = Y; Month = M; Day = D; } void Date::Display() //detail of member function { cout<<\"Year : \"<<Year<<endl; cout<<\"Month: \"<<Month<<endl; cout<<\"Date : \"<<Day<<endl; } ! ศิริชยั นามบุรี การเขียนโปรแกรมแบบ OOP

! 168 ผลการทํางานของโปรแกรม Display Constructor member function : OOP Programming Display Date from constructor member function //คา ทไ่ี ดเ กดิ จากการใช constructor Year : 1997 Month: 12 Date : 31 Display Date from setting value //คา ทไ่ี ดเ กดิ จากการกาํ หนดคา Year : 2540 Month: 10 Date : 22 เมอ่ื มกี ารสรา ง constructor ซึ่งจะทาํ ใหอ อบเจก็ ตส ามารถมคี า เรม่ิ ตน ทาํ งานไดโ ดยอตั โนมตั ไิ ด การยกเลิก constructor หรือยกเลิกการทํางานของออบเจก็ ตโ ดยอตั โนมตั ิ เพื่อยกเลิกการใชหนวยความ จาํ จะตอ งสรา งเมมเบอรฟ ง กช นั ชนดิ ทเ่ี รยี กวา ดิสตรกั เตอร (destructor) ซึ่งจะมีชื่อเดียวกับคอนสต รกั เตอรเ พยี งแตม เี ครอ่ื งหมาย ~ กาํ กับที่หนาชื่อฟงกชันไมมีพารามิเตอรและไมมีรายละเอียดในเครื่อง หมาย { } เชน class Date //create class Date { private: int Year; //data member int Month; //data member int Day; //data member public: Date() //constructor member function…function name same as class name { Year = 1997; //คาคงที่ของ data member ที่เปนคาเริ่มตน Month=12; Day=31; } ~Date() { }; //สรางดิสตรักเตอร void SetDate(int Y, int M, int D); //member function }; void Display(); //member function หมายเหตุ ทั้งฟงกชันประเภท คอนสตรกั เตอรแ ละดสิ ตรกั เตอร จะไมมีการสงคาออกจาก ฟงกชัน ! ศิริชัย นามบุรี การเขียนโปรแกรมแบบ OOP

! 169 ♦ค! ุณสมบัติการสืบทอด (inheritance) การสบื ทอด (inheritance) เปนคุณสมบัติสาํ คญั ของการเขยี นโปรแกรมเชงิ วตั ถเุ ปา หมาย (OOP) หมายถึง การถายทอดคุณสมบัติตาง ๆ ของออบเจก็ ตท เ่ี ปน ตน กาํ เนดิ หรอื บรรพบรุ ษุ ซง่ึ เราเรยี ก วา แอนเซสเตอร (ancestor) ไปยังออบเจ็กตทีเ่ ปน ลูกหลานหรือผูสบื ทอด เราเรยี กวา ดีเซนแด็นต (desendant) ไดห ลายออบเจก็ ต ทาํ ใหเกิดความสัมพันธระหวางคลาสและออบเจ็กตเปน ลําดับชั้นเหมือนกับการลาํ ดบั ความสมั พนั ธข องเครอื ญาติ การถายทอดคุณสมบัติของคลาสจะเริ่มจากคลาสเริ่มตน ที่เรยี กวา เบสคลาส (base class) หรอื แอนเซสเตอร (ancestor) ไปยังคลาสใหมที่สืบเนื่องจากคลาสเริ่มตน เรียกคลาสที่สืบเนื่องนี้วา ดี ไรฟคลาส (derived class) หรอื ดีเซนแด็นต (desendant) ดีไรฟคลาส (derived class) จะสืบทอดคุณสมบัติทั้งหมดของ ดาตา เมมเบอรแ ละเมมเบอร ฟงกชันที่มีอยูใน เบสคลาส (base class) ยกเวน คอนสตรกั เตอรแ ละดสิ ตรกั เตอร ลักษณะความสัมพันธระหวาง base class กับ derived class จะอยใู นรปู แบบ 4 ลักษณะ ดงั น้ี 1. หนึ่งดีไรฟคลาส สืบทอดคุณสมบัติจาก หนึ่งเบสคลาส ดงั รปู ! เบสคลาส D ! ดไี รฟค ลาส A 2. หลายดีไรฟคลาส สืบทอดคุณสมบัติจาก หนึ่งเบสคลาส ดงั รปู ! เบสคลาส D ! ดไี รฟค ลาส A ! ดไี รฟค ลาส B ! ดไี รฟค ลาส C ! ศิริชัย นามบุรี การเขียนโปรแกรมแบบ OOP

! 170 3. หนึ่งดีไรฟคลาส สืบทอดคุณสมบัติจาก หลายเบสคลาส ดงั รปู ! เบสคลาส A ! เบสคลาส B ! เบสคลาส C ! ดไี รฟค ลาส D 4. หลายดีไรฟคลาส สืบทอดคุณสมบัติตอเนื่องกันไปหลายลาํ ดับจาก หนึ่งเบสคลาส ดงั รปู ! เบสคลาส D ! ดไี รฟค ลาส A ! ดไี รฟค ลาส B ! ดีไรฟคลาส C รปู แบบการสรา ง ดีไรฟคลาส (derived class) จะมีรูปแบบและสวนประกอบตางๆ เหมอื นกับ การสรา ง เบสคลาส มีรปู แบบ ดงั น้ี class ชอ่ื ดไี รฟค ลาส : private หรอื public หรอื protected ชอ่ื เบสคลาส { private หรอื public หรอื protected : ดาตาเมมเบอร; ดาตาเมมเบอร; ดาตาเมมเบอร; private หรอื public หรอื protected : เมมเบอรฟ ง กช นั ; เมมเบอรฟ ง กช น่ั ; }; ! ศิริชัย นามบุรี การเขียนโปรแกรมแบบ OOP

! 171 ตัวอยางเชน การสรา งเบสคลาส ชื่อ Draw และสรา งดีไรฟคลาส ชื่อ Point class Draw //เบสคลาส { protected: int X, Y, Color; public: Draw(int InitX, int InitY, int InitColor) //คอนสตรกั เตอร { X = InitX; Y = InitY; Color = InitColor; } ~Draw() //ดสิ ตรกั เตอร { closegraph(); } }; class Point : public Draw //ดีไรนคลาสชื่อ Point สบื ทอดมาจากคลาส Draw { public: //คอนสตรักเตอรฟงกชันชื่อ Point Point(int InitX, int InitY, Int InitColor) : Draw(InitX, InitY, InitColor) {}; void Display(); void Hide(); }; การกําหนดเบสคลาสและดไี รฟค ลาสจากตวั อยา ง มคี วามหมายดงั น้ี - Draw เปน เบสคลาส มีคลาส Point เปน ดไี รฟค ลาส แสดงวาคลาส Point จะสามารถสืบ ทอดคณุ สมบตั ติ าง ๆ มาจากคลาส Draw ได - class Point : public Draw เปน ประโยคกําหนดใหคลาส Point เปนดีไรฟคลาสของคลาส Draw คําวา public กําหนดอยหู นาชอ่ื เบสคลาส Draw หมายถึง ออบเจก็ ตท ส่ี รา งโดยใช ดีไรฟคลาสนั้น จะสามารถเรียกใชสมาชิก (ดาตา เมมเบอรแ ละเมมเบอรฟ ง กช นั ) ของเบสคลาสในสวน ท่เี ปน public ไดทั้งหมด ตามตวั อยา ง ถา สรา งออบเจก็ ตช อ่ื Apoint จากดีไรฟคลาส Point Point Apoint; แสดงวา ออบเจต็ ก Apoint เปนออบเจ็กตที่สรางจากดีไรฟคลาสที่ชื่อ Point จะ สามารถเรียกใชฟงกชันในคลาส Draw ไดทุกฟงกชัน - protected: ในคลาส Draw หมายถึง สมาชิกของคลาส (อาจเปน ดาตา เมมเบอรห รอื เมมเบอร ฟงกชันก็ได) ที่อยูภายใตคําวา protected จะยอมใหดีไรฟคลาสของคลาสนี้เทานั้นที่สามารถเรียกใชได ! ศิริชยั นามบุรี การเขียนโปรแกรมแบบ OOP

! 172 ในตัวอยางแสดงวา นอกจากการเรียกใชสมาชิกในคลาส Draw ไดแลว คลาส Point จะสามารถเรียก ใชด าตาเมมเบอร X, Y และ Color ของคลาส Draw ไปใชไดดวย เนื่องจากคลาส Point เปน ดไี รฟค ลาส ของ Draw นน่ั เอง (เรียกวาลักษณะการสืบทอดคุณสมบัต)ิ ♦!ตวั อยา งการสบื ทอดคณุ สมบตั ใิ นโปรแกรม โปรแกรม INHER_EX.CPP แสดงการสืบทอดคุณสมบัติ (ฟงกชันและขอมูล) ของคลาสใน รปู แบบ หนึ่งเบสคลาสสืบทอดคุณสมบัติไปสูหลายดีไรฟคลาส มโี ครงสรา งการสืบทอด ดงั น้ี ! !(bavseehiccllaess) มี member function ! set_wheels() ! get_wheel() ! set_pass() ! get_pass() ! !(deส!!rรivาtteงr1du,octbkc2jleacsst1) ! !!(dสearรui!าtvoงemdcoocbbljaielscest2) ! มี member function มี member function ! set_cargo() ! set_type() ! get_cargo() ! get_type() ! show() ! show() จากโครงสรางการสืบทอดของเบสคลาส vehicle ไปสูดีไรฟคลาส คือ truck , automobile ไดมีเรียกใช object ที่สรางจากคลาส truck และ automobile แตเ รยี กใชค ณุ สมบัติหรือสบื ทอดคณุ สมบตั ิทเี่ ปน member function ของคลาส vehicle ซึ่งเปนเบสคลาส ในโปรแกรมดงั น้ี t1.set_wheels(18); t1.set_cargo(3200); t2.set_wheels(6); t2.set_pass(3); c.set_wheels(4); c.set_pass(6); •! ตวั อยางโปรแกรม INHER_EX.CPP เปนโปรแกรมแสดงการใชคุณสมบัติ Inheritance ของการเขียนโปรแกรมแบบ OOP ! ศิริชยั นามบุรี การเขียนโปรแกรมแบบ OOP

! 173 /*Program : INHER_EX.CPP Process : show inheritance from base class to derived class class vehicle --> class turck, automobile */ #include <iostream.h> #include <conio.h> class vehicle //base class { int wheels; int passengers; public: //declared public function in class void set_wheels(int num); int get_wheels(); void set_pass(int num); int get_pass(); }; class truck:public vehicle //derive class of class vehicle { int cargo; public: void set_cargo(int size); int get_cargo(); void show(); }; enum type_auto{car,van,wagon}; //set enumerated data type class automobile:public vehicle //derive class of class vehicle { type_auto car_type; //enumerated variable public: void set_type(enum type_auto t); enum type_auto get_type(); void show(); }; void vehicle::set_wheels(int num) { wheels=num; } int vehicle::get_wheels() { return wheels; } ! ศิริชัย นามบุรี การเขียนโปรแกรมแบบ OOP

! 174 การเขียนโปรแกรมแบบ OOP void vehicle::set_pass(int num) { passengers=num; } int vehicle::get_pass() { return passengers; } //begin created member function of truck class void truck::set_cargo(int num) { cargo=num; } int truck::get_cargo() { return cargo; } void truck::show() { cout<< \"Wheels : \"<<get_wheels()<<\"\\n\"; cout<< \"Passengers : \"<<get_pass()<<\"\\n\"; cout<< \"Cargo capacity in cubic feet : \"<<cargo<<\"\\n\"; } //begin created member function of automobile class void automobile::set_type(enum type_auto t) { car_type=t; } type_auto automobile::get_type() { return car_type; } void automobile::show() { cout<<\"Wheels : \"<<get_wheels()<<\"\\n\"; cout<<\"Passengers: \"<<get_pass()<<\"\\n\"; ! ศิริชยั นามบุรี

! 175 cout<<\"Type : \"; switch(get_type()) { case van: cout<<\"Van\\n\";break; case car: cout<<\"Car\\n\";break; case wagon: cout<<\"Wagon\\n\";break; } } void main() //Begin main program { clrscr(); cout<<\"Display Inheritance from Class vehicle to truck and automobile....\"<<endl<<endl; truck t1,t2; //created object...t1 and t2 from class truck automobile c; //created object...c from class automobile //used object and called function member t1.set_wheels(18); //use inheritance set_wheels() from based class...vehicle t1.set_pass(2); //use inheritance set_pass() from based class...vehicle t1.set_cargo(3200); //use function set_cargo() from derived class...truck t2.set_wheels(6); //use inheritance set_wheels from based class...vehicle t2.set_pass(3); //use inheritance set_pass() from based class...vehicle t2.set_cargo(1200); //use function set_cargo() from derived class...truck t1.show(); //use function show() derived class...truck cout<<endl; t2.show(); //use function show() derived class...truck c.set_wheels(4); //use inheritance set_wheels() from base class...vehicle c.set_pass(6); //use inheritance set_pass() from base class...vehicle c.set_type(van); //use function set_type() from derived class...automobile cout<<endl; c.show(); //use function show() from derived class...automobile getch(); } ผลการ run โปรแกรม เปน ดงั น้ี Display Inheritant from Class vehicle to truck and automobile.... การเขียนโปรแกรมแบบ OOP Wheels : 18 ! ศิริชยั นามบุรี

! 176 Passengers : 2 Cargo capacity in cubic feet : 3200 Wheels : 6 Passengers : 3 Cargo capacity in cubic feet : 1200 Wheels : 4 Passengers: 6 Type : Van •! ตัวอยางโปรแกรม Dra_cir2.cpp แสดงการถายทอดคุณสมบัติ (inheritance) จากเบส คลาส Draw ไปสูดีไรฟคลาสที่ชื่อ Point /*Program : Dra_cir2.cpp Process : display and hide point from derived class */ #include <iostream.h> #include <stdlib.h> #include <graphics.h> #include <conio.h> class Draw //base class { protected: //ใชไดเฉพาะในเบสคลาสและดีไรฟคลาส int X, Y, Color; public: Draw(int InitX, int InitY, int InitColor) //construture { X=InitX; Y=InitY; Color=InitColor; } ~Draw() //destructure function การเขียนโปรแกรมแบบ OOP { closegraph(); //close graphic mode } ! ศิริชัย นามบุรี

! 177 }; class Point : public Draw //derived class { public: Point(int InitX,int InitY,int InitColor):Draw(InitX,InitY,InitColor){} void Display(); void Hide(); }; void main() { /* request auto detection graphic display hardware*/ int gdriver = DETECT, gmode, errorcode; /* initialize graphics mode */ initgraph(&gdriver, &gmode, \"\"); //create object from derived class and inheritance attribute Point Apoint(320,240,WHITE); //สรางออบเจ็กตชื่อ Apoint Apoint.Display(); //function for display white point on screen getch(); Apoint.Hide(); //function for display background color point on screen Apoint.Display(); getch(); } void Point::Display() { putpixel(X,Y,Color); } void Point::Hide() { putpixel(X,Y,getbkcolor()); } ♦แ! บบฝกหัดทายบท ! ศิริชยั นามบุรี การเขียนโปรแกรมแบบ OOP

! 178 1. ใหนักศึกษาเขียนโปรแกรมแบบ OOP เพื่อคํานวณคาและแสดงผลลัพธพื้นที่ของรูปเรขาคณิต โดย ใหสรางเมมเบอรฟงกชันของคลาสเพื่อทาํ หนาที่คาํ นวณคาของพื้นที่และแสดงผล ดงั ตอ ไปน้ี - พื้นที่รูปสี่เหลี่ยม - พื้นที่รูปสามเหลี่ยม - พื้นที่วงกลม 2. ใหเ ขยี นโปรแกรมเพอ่ื จดั เกบ็ ขอ มลู ประวตั พิ นกั งานไมเ กนิ 100 คน มีรายละเอียดขอมูลไดแก รหัสพนักงาน, ชื่อพนักงาน และเงนิ เดอื น โดยกําหนดใหม ี member function สาํ คัญ ๆ ดงั น้ี - Input() ทาํ หนา ทร่ี บั ขอ มลู รหัสพนักงาน, ชอ่ื พนกั งานและเงนิ เดอื น - Cal_Net_Tax() ทาํ หนาที่คาํ นวณภาษีหัก ณ ทจ่ี า ยจากเงนิ เดอื น 7% และคาํ นวณเงนิ เดอื น คงเหลือสุทธิ - Cal_Total() ทาํ หนาที่คํานวณเงนิ เดอื นรวม, ภาษรี วม, เงินคงเหลือสุทธิรวมของพนักงาน ทุกคน - Report() ทาํ หนาที่แสดงรายงานที่มีรายละเอียดขอมูล รหัสพนักงาน, ชื่อพนักงาน, เงนิ เดอื น, ภาษีหัก ณ ที่จาย, เงินเดือนเหลอื สทุ ธขิ องพนักงานแตละคน และยอดสรปุ รวมเงนิ เดอื น, ภาษีหัก ณ ทจ่ี า ยรวม และเงนิ เดอื นสทุ ธริ วม 3. ใหเ ขยี นโปรแกรมคํานวณการตดั เกรดแบบองิ เกณฑ โดยใชว ธิ กี ารเขยี นโปรแกรมแบบ OOP ใหโ ปรแกรมมคี วามสามารถ ดงั ตอ ไปน้ี - รับขอมูลรหัสนักศึกษา, ชื่อนักศึกษา, คะแนนระหวางภาค, คะแนนปลายภาค - คํานวณการตดั เกรดตามเกณฑ คะแนนดงั น้ี 0-49 เกรด F 50-59 เกรด D 60-69 เกรด C 70-79 เกรด B 80-100 เกรด A - แสดงรายละเอียดที่กรอกทั้งหมด พรอ มแสดงคะแนนรวมและเกรดทไ่ี ด ขอ กาํ หนด ใหโปรแกรมสามารถเก็บขอมูลนักศึกษาพรอมกันไดไมเกิน 100 คน ! ศิริชยั นามบุรี การเขียนโปรแกรมแบบ OOP

บทที่ 12 การจดั การขอมูลแบบไฟล ❐ ความหมายของไฟล ไฟล( File) หมายถึง โครงสรา งของกลมุ ขอ มลู ทจ่ี ดั เกบ็ ในรปู แบบทค่ี อมพวิ เตอรส ามารถนํามา ใชงานได ไฟลอ าจถกู จัดเกบ็ อยใู นหนวยความจําหรอื สอ่ื บนั ทกึ ขอ มลู เชน แผนดิสก ฮารด ดสิ ก หรอื CD-ROM ซึ่งสามารถนําขอมูลในไฟลที่บันทึกในสื่อดังกลาวกลับมาใชใหมไดอีก นอกจากนั้นขอมูลใน ไฟลส ามารถสงออกไปแสดงผลทจ่ี อภาพ หรอื เครอ่ื งพมิ พ โดยอาศยั การจดั การดว ยโปรแกรมทม่ี คี าํ สั่ง เกี่ยวกับการจัดการไฟลโดยเฉพาะ ❐ ชนิดของไฟลใน C++ 1. Text File หมายถึง ไฟลที่ประกอบดวยตัวอักษร เครอ่ื งหมายตา ง ๆ ที่ใชในขอความ มีการ กําหนดรหสั การจบแตล ะบรรทดั ดว ยรหสั แปน enter หรอื รหสั การขน้ึ บรรทดั ใหม( carriage return) และมี เครื่องหมายจบไฟล (end of file maker) โดยทั่วไป Text File จะเปน ไฟลท ส่ี รา งขน้ึ จากโปรแกรม ประเภท Text Editor หรอื Word Processor เชน ไฟลชนิด .CPP ก็สรางจาก Text Editor ของ C++ ดงั นน้ั จงึ สามารถ Text File ไปเปด ในโปแกรมประเภท Word Processor ได ใชคาํ สั่ง Type ของ DOS ดูรายละเอียดในไฟลได 2. Binary File หมายถึง ไฟลทป่ี ระกอบดว ยของมลู ประเภทโครงสรา ง (Structure) หรอื มกี ารบบี ลดขนาด (Compress) ซึ่งทาํ ใหขอมูลมีลักษณะแตกตางจากขอมูลใน Text File การสรา ง Binary File จะสรางจากโปรแกรมสาํ หรบั ไฟลชนดิ นน้ั โดยเฉพาะ เพื่อความสะดวกในการอาน และเขียนไฟล เชน ไฟลใ นโปรแกรม dBASE, Lotus เปน ตน ❐ การดําเนนิ การเกย่ี วกบั ไฟล ใน C++ มีคลาสที่ทาํ หนาที่เกี่ยวกับการรับขอมูลและการนาํ ขอ มลู ออกจากไฟล (File I/O) อยู 3 คลาส ไดแก - คลาส ifstream ทาํ หนาที่รับขอมูลจากไฟลเขามาในหนวยความจํา - คลาส ofstream ทาํ หนา ทน่ี าํ ขอมูลจากหนวยความจําสงออกไปที่ไฟล - คลาส fstream ทาํ หนาที่ทั้งรับขอมูลจากไฟลเขามาในหนวยความจาํ และนําขอมูลจากหนวย ความจําออกไปที่ไฟล ศิริชยั นามบรุ ี การจดั การขอ มลู แบบไฟล

180 ทั้ง 3 คลาส คือ ifstream, ofstream, stream เก็บอยูในไฟล fstream.h ดงั นน้ั โปรแกรมทม่ี กี าร ดาํ เนินการเกี่ยวกับขอมูลประเภทไฟล จะตองมีการ include เฮดเตอรไ ฟล ที่ชื่อ fstream.h ดว ยเสมอ ในการดาํ เนินการเกี่ยวกับไฟล ทั้ง Text File และ Binary File มกี ิจกรรมหลกั ๆ ทต่ี อ งดาํ เนนิ การ คือ การบันทึกขอมูลจากหนวยความจําเขาเก็บในไฟล และการอานขอมูลจากไฟลมาไวในหนวยความจาํ ❐ วิธีดาํ เนนิ การกบั ไฟลข อ มลู สตรงิ (Text File) 1. การบันทึกสตริงเขาไฟลในดิสก ทาํ ไดโดยการสรางออบเจ็กตใหเปนสมาชิกของคลาส ofstream และกาํ หนดชื่อไฟล ตามรปู แบบตวั อยา ง ofstream WriteTextFile(“A:INFO.TXT”); class object ชื่อไดรฟและชอื่ ไฟล จากรปู แบบ ofstream คือชื่อคลาส WriteTextFile คอื ชอ่ื ออบเจก็ ตท ส่ี รา งขน้ึ เพอ่ื ทาํ หนาที่บันทึกไฟลและในวงเล็บ (“test1.txt”) คือชื่อไฟล ซึ่งเปน Text File ที่จะใชบันทึกขอความ ถา ไมร ะบไุ ดเรกทอรจ่ี ะบันทกึ ลงในไดเรกทอรปี จจุบนั เราสามารถเขียนออกเจก็ ตสาํ หรับทาํ หนาที่ บันทึกสตริงเขาไฟลในลักษณะอื่นๆ ได เชน ofstream SaveTextFile(“A:Test.txt”); ofstream write_text_file(“A:\\DATA\\test.dat”); วิธีการบันทึกสตริงเขาเก็บไวในไฟล เขยี นไดด งั น้ี WriteTextFile<<“Hello, I love C++ and Computer\\n”; หมายถึงใหบันทึกขอความ Hello, I love C++ and Computer ไวในไฟล data.txt เปน ตน ตัวอยางโปรแกรม TEXTFILE.CPP แสดงการบันทึกขอความเขาเก็บไวในไฟล ชื่อ INFO.TXT ในไดเรกทอรี A: การแสดงผลลพั ธข องโปรแกรมจะทําการบันทกึ ขอความที่กาํ หนดไวในไฟล INFO.TXT ซึ่งเราสามารถดูเนื้อหาในไฟลได โดยการใชคําสั่ง ใน DOS prompt A:\\>TYPE INFO.TXT [กด enter] หรอื เปดไฟลโดยใช Editor ของ C++ โดยใชคําสั่ง File / Open พิมพชื่อไฟล A:INFO.TXT แลว OK หรอื enter ศิริชยั นามบรุ ี การจดั การขอ มลู แบบไฟล

181 /*Program: TextFile.CPP Process: write text line to text file A:INFO.TXT */ #include <iostream.h> #include <fstream.h> void main() { //create WriteTextFile object from ofstream class ofstream WriteTextFile(\"A:INFO.TXT\"); WriteTextFile<<\" Hello, How are you today? \\n\"; WriteTextFile<<\" How do you feel about C++? \\n\"; WriteTextFile<<\" I hope that you will fall in love it.\\n\"; WriteTextFile<<\" Are you O.K. \"; } ขอ สงั เกต การใชคลาส ofstream สรา งออบเจก็ ต เพื่อบันทึกสตริงก ออปเจก็ ตจ ะทาํ การเปด บนั ทึกขอ มลู แลวปด ไฟลใ หโดยอัตโนมตั ิ 2. การอานสตริงจากไฟลในดิสก ทาํ ไดโดยการ 2.1 ตอ งสรา งออบเจก็ ตใ หเ ปน สมาชกิ ของคลาส ifstream และกาํ หนดชื่อไฟลที่ตองการ อา นขอ มลู ตามรปู แบบดงั น้ี ifstream ReadTextFile(“A:INFO.TXT”); class object ช่ือไดรฟแ ละชอื่ ไฟล หมายถึง สรา งออบเจก็ ตช อ่ื ReadTextFile เปนสมาชิกของคลาสifstream เพอ่ื ดาํ เนนิ การอา นสตรงิ จากไฟลช อ่ื ชอ่ื Test1.txt จากไดเรกทอรป่ี จ จบุ นั 2.2 ใชฟงกชัน getline() ที่เปนสมาชิกของคลาส istream ซึ่งเปนดีไรฟคลาสของ ifstream ฟงกชัน getline() ทาํ หนา ท่อี า นอกั ษรจากไฟลม าเกบ็ ไวใ นตวั แปรประเภท charทีละบรรทัด (‘\\n’) จาํ นวนสูงสุดตามที่กาํ หนด ตามรปู แบบดงั น้ี ReadTextFile.getline(ALine,Maxchar); object function argument หมายถึง ออบเจก็ ต ReadTextFile มีการอานสตริงจากไฟล Test1.txt ดว ย ฟงกชัน getline() อานมาทีละบรรทัดมาเก็บไวที่ตัวแปร ALine จํานวนที่เก็บไดสูงสุดในแตละบรรทัดเทา กับ Maxchar ศิริชยั นามบรุ ี การจดั การขอ มลู แบบไฟล

182 •! ตัวอยางโปแกรม READTXT1.CPP ตอไปนี้ ทาํ หนาที่ในการอานขอมูลจาก Text File ชื่อ INFO.TXT ขน้ึ มาทลี ะบรรทดั แตละบรรทัดไมเกิน 80 ตัวอักษร จนกวาจะจบไฟลหรอื จน กวาจะอานขอมูลไมไดอีกแลว /*Program: TXTREAD1.CPP Process: read text file to string of character or to line */ #include <fstream.h> #include <iostream.h> #include <conio.h> void main() { char text[80]; clrscr(); //ReadTextFile() is object that user create from ofstream class ifstream ReadTextFile(\"A:INFO.TXT\"); while(ReadTextFile) { ReadTextFile.getline(text,80); cout<<text<<endl; } cout<<\"this is text that read from A:INFO.TXT file\\a\"; getch(); } หมายเหตุ while(ReadTextFile) เปน คาํ สั่งแบบลูป(Looping) ทาํ หนาที่อานขอมูลจนจบไฟล โดยฟงกชัน getline() จะอา นขอ มลู 1 บรรทดั มาเกบ็ ไวท ต่ี วั แปร text แลวแสดงออกไปที่จอภาพดวยคาํ สั่ง cout<< ตามเงอ่ื นไข ตรวจสอบการจบไฟลด ว ยออบเจก็ ต ReadTextFile มีการทาํ งานดงั น้ี - ถาจบไฟล ReadTextFile จะใหคาเปน 0 - ถายังไมจบไฟล ReadTextFile จะใหคาที่ไมใช 0 ศิริชัย นามบรุ ี การจดั การขอ มลู แบบไฟล

183 ❐ วิธีดาํ เนนิ การกบั ไฟลอกั ษร 1. การบันทึกตัวอักษรเขาไฟลในดิสก ทาํ ไดโดยใชฟงชชัน put() ซึ่งเปนฟงกชันในคลาส ostream ใชสาํ หรับบันทึกอักษรเขาไฟลครั้งละ 1 ตวั อกั ษร มีรูปแบบของฟงกชัน put()ดงั น้ี Parameters ofstream& put(char ch); class function ฟงกชัน put() จะทาํ หนาที่สง ch ไปบันทึกในไฟลที่กาํ หนด ตัวอยางโปรแกรม CharFil1.CPP ใชฟงกชัน put() ทาํ การบันทึกตัวอักษรจากขอความครั้งละ 1 ตัวอักษรบันทึกลงในไฟล A:INFO2.TXT /*Program: CharFil1.CPP Process: write character to file */ #include <fstream.h> #include <string.h> void main() { char Str[]=\"I love to learn C++ Language\"; ofstream WriteTextFile(\"A:INFO2.TXT\"); for(int n=0;n<strlen(Str);n++) WriteTextFile.put(Str[n]); } ศิริชัย นามบรุ ี การจดั การขอ มลู แบบไฟล

184 •! ตัวอยางโปรแกรม WriteCha.CPP ทําหนา ทร่ี บั ขอ มลู ครง้ั ละตวั อกั ษรและเขยี น ลงไฟลA:INFO3 จนกวาจะกดแปน Enter จากนั้นอานขอมูลจากไฟล /*Program: WriteCha.CPP Process: write for each character to text file by put() function */ #include <fstream.h> #include <iostream.h> #include <conio.h> #include <string.h> void main() { char ch; clrscr(); ofstream WriteTextFile(\"A:INFO3.TXT\"); cout<<\"**** Please key character ....press enter to stop ****\"; cout<<endl; while(ch!=13) { ch=getche(); //input 1 character to ch WriteTextFile.put(ch); //write to file } WriteTextFile.close(); clrscr(); //ReadTextLine() is object that user create from ifstream char chr; ifstream ReadTextLine(\"A:INFO3.TXT\"); while(ReadTextLine); { ReadTextLine.get(chr); cout<<chr; } cout<<endl<<endl<<\"....this is text that read from INFO3.TXT getch(); } ศิริชัย นามบรุ ี การจดั การขอ มลู แบบไฟล

185 ❐ วิธีดาํ เนนิ การกบั ไบนารไี ฟล (Binary File) Binary File เปนไฟลที่ประกอบดวยของมูลประเภทโครงสราง (Structure) หรือมีการบีบลด ขนาด (Compress) ไฟลประเภทนี้จะใชกับขอมูลชนิด structure มีการจัดการ ดงั น้ี 1. การเขียนขอมูลลงไฟลในดิสก ใชฟงกชัน write() ซึ่งเปนฟงกชันในคลาส ostream ฟงกชัน write() มรี ปู แบบดงั น้ี ostream& write(const char* , int n); ฟงกชัน write() จะนําตวั อกั ษรจากพารามเิ ตอรต วั ท่ี 1 จํานวน n ตัวอักษาไปเขียนไฟลใน ไฟล โดยในจาํ นวน n ตวั นร้ี วมอกั ษร Null ไวแลว 2. การอานขอมูลจากไฟล ทาํ ไดโดยใชฟงกชัน read() ซึ่งเปนฟงกชันในคลาส istream มรี ปู แบบดงั น้ี istream& read(const char* , int n); ฟงกชัน read() จะอา นอกั ษรจากไฟลมาเกบ็ ไวทพ่ี ารามเิ ตอรตัวท่ี 1 โดยมจี ํานวน อักษรตามที่กําหนดไวใ นพารามเิ ตอรต วั ท่ี 2 •! ตวั อยา งโปรแกรม STD_FILE.CPP มีการสราง class และขอ มลู ชนดิ structure เพื่อนําไปบันทึกในไฟลขอมูลในไดรฟ A: ชื่อ student.dat โดย บันทึกขอมูลไดเพียงครั้งละ 1 ชดุ หรอื 1 เรคอรด (record) /*Program: STD_FILE.CPP Process:Create Class Create Binary File Read Binary File Create Menu() Function */ #include <fstream.h> #include <iostream.h> #include <conio.h> #include <string.h> //prototype function void Menu(); void Create(); ศิริชัย นามบรุ ี การจดั การขอ มลู แบบไฟล

186 void Display(); //creat class class STD { protected: // data member char code[9]; char name[40]; int age; public: void InputData() //member function { cout<<\"Enter Code : \";cin>>code; cout<<\"Enter Name : \";cin>>name; cout<<\"Enter Age : \";cin>>age; } void ShowData() //memdber function { cout<<\"Enter Code : \"<<code<<endl; cout<<\"Enter Name : \"<<name<<endl; cout<<\"Enter Age : \"<<age<<endl; getch(); } }; STD Student; //create Object student from STD class //begin main function void main() { Menu(); } void Menu() //user defined function { char choice=' '; while(choice!='3') ศิริชัย นามบรุ ี การจดั การขอ มลู แบบไฟล

187 การจดั การขอ มลู แบบไฟล { clrscr(); gotoxy(25,2);cout<<\"Main Menu Student Data\"; gotoxy(30,4);cout<<\" 1. Create File and Input Data\"; gotoxy(30,5);cout<<\" 2. Displa Data File \"; gotoxy(30,6);cout<<\" 3. Exit \"; gotoxy(30,8);cout<<\"Select choice : \";choice=getch(); switch(choice) { case '1': Create(); break; case '2': Display(); break; case '3': break; } } } void Create()//user defined function { clrscr(); Student.InputData(); ofstream WriteFile(\"A:student.dat\"); //create file WriteFile.write((char*)&Student,sizeof(Student)); //write data to file } void Display()//user defined function { clrscr(); ifstream ReadFile(\"A:student.dat\"); //open file ReadFile.read((char*)&Student,sizeof(Student)); //read data from file Student.ShowData(); ReadFile.close(); } ศิริชัย นามบรุ ี

188 ❐ วิธีดาํ เนนิ การกบั ไฟลพ อยนเ ตอร (File Pointer) เน่อื งจากการจัดการกับขอ มูลของไฟลประเภท Binary หลาย ๆ ออบเจก็ ตห รอื หลาย ๆ เรคอรด ไมสามารถทําไดหากใชเฉพาะฟงกชัน write() หรอื read() เพียงอยางเดียว แตจ ะตอ งใช File Pointer ใน การจัดการ โดยใชฟงกชัน open() เปด ไฟลใ นโหมดตา ง ๆ ซึ่งมีรูปแบบดังนี้ void open(const char* name, int mode, int prot =filebuff::openprot); โดยท่ี name คือ ชอื่ ไฟลท่ตี องการเปด mode คือ โหมดการเปด เพอ่ื วตั ถปุ ระสงคต า ง ๆ ดงั ตารางดงั น้ี โหมด ความหมาย in เปด ไฟลเ พอ่ื อา นขอ มลู out เปดไฟลเพื่อบันทึกขอมูล app เร่มิ อา นหรอื บันทึกไฟลตอนทา ยไฟล ate ลบไฟลกอนที่จะอานหรือเซฟไฟล nocreate จะเกิดความผิดพลาถาเปดไฟลที่ไมมีอยู noreplace จะเกิดความผิดพลาดถาเปดไฟลที่มีอยูเพื่อเซฟขอมูล binary เปดไฟลไบนารี โดยท่ี โหมดเหลา นส้ี ามารถใชร ว มกนั ไดโ ดยใชเ ครอ่ื งหมาย | คน่ั ระหวา งแต ละโหมด เชน open(“TEST.DAT”,ios::in|ios::out); prot คือ วธิ กี ารตดิ ตอ กบั DOS ซึ่งตามปกติถาไมกําหนด ใหต ดิ ตอ กบั DOS เพ่ือบนั ทึกหรืออานขอ มลู จากไฟล การสรา งไฟลแ ละการอา นไฟลพ อยนเ ตอร มขี น้ั ตอนสาํ คัญ ดังนี้ 1. สรางคลาสหนดขอมูลและฟงกชัน สรางคลาสเพื่อกาํ หนดขอ มลู ชนดิ structure ภายในคลาส ศิริชยั นามบรุ ี การจดั การขอ มลู แบบไฟล

189 พรอ มทง้ั สรา ง Member Function ตา ง ๆ ทต่ี อ งการในโปรแกรม เชน class Person { protect: char Name[50] int Age; public: void GetData() //ฟง กช นั ทําหนา ทร่ี บั ขอ มลู { cout<< “Enter Name : “; cin>>Name; cout<< “Enter Age : “; cin>>Age; } void ShowData() //ฟง กช นั ทําหนา ทแ่ี สดงขอ มลู { cout<<”Name : “<<Name<<endl; cout<<”Name : “<<Age<<endl; } }; 2. สรา งออบเจก็ ตท เ่ี ปน record ขอมูลจากคลาสที่สรางไวในขอ 1 Person Student; //Person คือ คลาส และ Student คอื ออบเจก็ ต 3. การสรา งออบเจก็ ตป ระเภทไฟล คือ การสรา งออบเจก็ ตป ระเภทไฟลจากคลาส fstream fstream File; //fsteram คือ คลาส และ File คือออบเจ็กตที่กําหนดขน้ึ 2. การเปด ไฟลใ นโหมดตา ง ๆ ดวยฟงกชัน open() โดยกําหนดโหมดตามความตอ งการ ดงั ตวั อยาง File.open(“A:TEST.DAT”,ios::app|ios::out|ios::in); 3. การเขียนหรือบันทึกขอมูลลงไฟล ดวยฟงกชัน write() ดงั น้ี File.write((char*)&Student,sizeof(Student)); 4. การอานขอมูลจากไฟล ดวยฟงกชัน read() ดงั น้ี File.read((char*)&Student,sizeof(Student)); 5. การกาํ หนดตําแหนงของขอมูลในไฟล ดวยฟงกชัน tellg(), seekg(), tellp(), seekp() การจัดการขอมูลในไฟล ณ ตาํ แหนง ตา ง ๆ ที่กาํ หนดของไฟล เรยี กวา ไฟลพอยนเ ตอร ตองใชฟงกชันตาง ๆ ทีเ่ กย่ี วขอ งกบั การระบุตําแหนงขอมูลในไฟล มรี ปู แบบ ดงั น้ี ศิริชัย นามบรุ ี การจดั การขอ มลู แบบไฟล

190 long tellg(); ใหค า ตําแหนง ของไฟลพ อยนเ ตอรซ ง่ึ เปน ตําแหนง อา นขอ มลู istream& seekg(sreampos pos) ใหเ ลอ่ื นไฟลพ อยนเ ตอรไ ปยงั ตําแหนง ทต่ี อ งการอา น ขอ มลู เชน File.seekg(0) หมายถึงเลื่อนไปยังตําแหนง เรคอรด หมายเลข 0 ซง่ึ เปน ตําแหนงแรกของไฟล ซง่ึ เรม่ิ จาก 0, 1, 2, ... streampos tellp(); ใหค า ตําแหนง ของไฟลพ อยนเ ตอรซ ง่ึ เปน ตําแหนง บันทกึ ขอ มลู ostream& seekp(streampos); จะเลอ่ื นไปทต่ี าํ แหนง ของไฟลพ อยนเ ตอรซ ง่ึ เปน ตาํ แหนงบนั ทึกขอ มลู ตวั อยา งโปรแกรม File_poin แสดงการใช File pointer จัดเก็บขอมูลพรอ มกันไดหลายเรคอรด (Record) บันทึกขอมูล, อานขอมูลและคนหาขอมูลจากไฟล /*Program: FIL_POIN.CPP Process:Create Class Create Binary File by pointer Create Menu() Function Write,Read, Search Record */ #include <fstream.h> #include <iostream.h> #include <conio.h> #include <string.h> #include <ctype.h> //prototype function void Menu(); void InputData(); void ReportData(); void SearchByCode(); //creat class class STD { public: // data member char code[9]; char name[40]; int age; public: void InputData() //member function ศิริชยั นามบรุ ี การจดั การขอ มลู แบบไฟล

191 { cout<<\"\\nEnter Code : \";cin>>code; cout<<\"Enter Name : \";cin>>name; cout<<\"Enter Age : \";cin>>age; } void ShowData() //memdber function { cout<<\"Code : \"<<code<<endl; cout<<\"Name : \"<<name<<endl; cout<<\"Age : \"<<age<<endl; } }; //global variable STD Student; //create Object student from STD class fstream File; //creat Object File from fstream class //begin main function void main() { Menu(); } void Menu() { char choice=' '; while(choice!='4') { clrscr(); gotoxy(25,2);cout<<\"Main Menu Student Data <<A:Student.dat>>\"; gotoxy(30,4);cout<<\"1. Appen Data \"; gotoxy(30,5);cout<<\"2. Report Data \"; gotoxy(30,6);cout<<\"3. Search Data from File \"; // gotoxy(30,7);cout<<\"4. Search Data from File \"; gotoxy(30,7);cout<<\"4. Exit \"; gotoxy(30,10);cout<<\"Select choice : \";choice=getch(); ศิริชัย นามบรุ ี การจดั การขอ มลู แบบไฟล

192 switch(choice) { case '1': InputData(); break; case '2': ReportData(); break; case '3': SearchByCode(); case '4': break; } } } void InputData() { char ans=' '; File.open(\"A:student.dat\",ios::app|ios::out|ios::in); clrscr(); cout<<\" Enter information of student: \"<<endl; while(toupper(ans)!='N') { Student.InputData(); File.write((char*)&Student,sizeof(Student)); cout<<\"Append data any more? <y/n> ? \"; ans=getch();cout<<endl; } File.close(); } void ReportData() { int all_rec=0,rec_no=1; //skip pointer of record at record #0 clrscr(); ศิริชัย นามบรุ ี การจดั การขอ มลู แบบไฟล

193 การจดั การขอ มลู แบบไฟล File.open(\"A:student.dat\",ios::app|ios::out|ios::in); File.seekg(0,ios::end); all_rec=File.tellg()/sizeof(Student); File.seekg(0,ios::beg); cout<<\"Report all record form file ....\"<<endl; cout<<\"Total record : \"<<all_rec<<endl; File.read((char*)&Student,sizeof(Student)); //read first record while(!File.eof()) { cout<<\"record# \"<<rec_no<<endl; Student.ShowData(); File.read((char*)&Student,sizeof(Student)); //read next record cout<<\"press any key...\"<<endl<<endl; getch();rec_no++; } cout<<\"end of file\\a\";getch(); File.close(); } void SearchByCode() { char co[9]; int recno=0; cout<<\"\\n\\nEnter code to search: \";cin>>co; File.open(\"A:student.dat\",ios::in); File.seekg(0,ios::beg); File.read((char*)&Student,sizeof(Student)); //read record search no# while(!File.eof()&&strcmp(co,Student.code)) { //File.seekg((i+1)*sizeof(Student)); File.read((char*)&Student,sizeof(Student)); //read record search no# } if((strcmp(co,Student.code)==0)) { cout<<\"\\nRecord found #: \"<<File.tellg()/sizeof(Student)<<endl; Student.ShowData(); } else cout<<\"Record not found!!!\\a\\a\"; ศิริชยั นามบรุ ี

194 cout<<\"\\npress any key to continue...\";getch(); File.close(); } ❐ แบบฝกหัดทายบท 1. ใหเ ขยี นโปรแกรมเพอ่ื เกบ็ ประวตั พิ นกั งานของบรษิ ทั แหง หนง่ึ รายละเอียดขอมูลที่จัดเก็บไดแก - รหัสพนักงาน - ชื่อสกุล - ที่อยู - อายุ - เงนิ เดอื น - ตาํ แหนง จากรายละเอียดของขอมูลใหเขียนโปรแกรมโดยใชขอมูลแบบไฟล ใหโ ปรแกรมมฟี งกช ันตา ง ๆ ในโปรแกรมทาํ งานตามหนาที่ ดงั น้ี - บันทึกประวัติพนักงาน - แสดงรายงานรายละเอียดประวัติของพนักงานทุกคนได - แสดงรายงานเงินเดือนพนักงานแตละคนและ รายละเอยี ดการหักภาษี ณ ที่จาย 3% ของ พนักงาน พรอ มยอดสรปุ คา เฉลย่ี เงนิ เดอื นของพนกั งาน - คน หาประวตั พิ นกั งานเปน รายบคุ ล โดยการกรอกรหสั พนกั งานเพอ่ื คน หาได 2. ใหน กั ศึกษาเขยี นโปรแกรมเพื่อคาํ นวณการตดั เกรดนกั ศกึ ษา โดยจดั เก็บขอ มูลเปนชนิดไฟลขอมูล กาํ หนดเงอ่ื นไขการตดั เกรด ดงั น้ี คะแนนระหวา ง 1-49 เกรด F คะแนนระหวา ง 50-59 เกรด D คะแนนระหวา ง 60-69 เกรด C คะแนนระหวา ง 70-79 เกรด B คะแนนระหวา ง 80-100 เกรด A โปรแกรมมคี วามสามารถดงั น้ี - บันทึกรายละเอียด รหสั , ชื่อนักศึกษา, คะแนนระหวา งภาค, คะแนนปลายภาค ลงไฟลขอมูล ศิริชัย นามบรุ ี การจดั การขอ มลู แบบไฟล

195 - รวมคะแนนจากแฟม ขอ มลู เพอ่ื นําไปคาํ นวณตดั เกรด - คํานวณการตดั เกรดตามเกณฑท ก่ี าํ หนดไว - คาํ นวณจํานวนคนทไ่ี ดร บั เกรดแตล ะเกรด - แสดงรายงานผลรายละเอยี ดขอ มลู การตดั เกรดทง้ั หมด พรอ มการสรปุ จํานวนผไู ดร ับในแตล ะ เกรด โดยทก่ี ารเขยี นโปรแกรมจะตอ งสรา งเปน ฟง กช นั แบง ตามหนา ทก่ี ารทํางานในโปรแกรมใหเ หมาะ สม ศิริชัย นามบรุ ี การจดั การขอ มลู แบบไฟล


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook