2013-2 Ch 6. Structures and Classes September 1, 2013 Advanced Networking Technology Lab. (YU-ANTL) Dept. of Information & Comm. Eng, Graduate School, Yeungnam University, KOREA (Tel : +82-53-810-2497; Fax : +82-53-810-4742 http://antl.yu.ac.kr/; E-mail : ytkim@yu.ac.kr)
Struct ( 구조체 ) Outline Classes Defining, member functions Public and private members Accessor (i.e., get_xx()) and mutator (i.e., set_xx())functions Structures vs. classes ch 6-2
Structures ( 구조체 ) 2 nd aggregate data type: struct Recall: aggregate meaning "grouping" Recall array: collection of values of same type Structure: collection of values of different types Treated as a single item, like arrays Major difference: Must first "define" struct Prior to declaring any variables ch 6-3
Structure Types Define struct globally (typically) No memory is allocated Just a "placeholder" for what our struct will "look like" Definition: typedef struct MyCmplx { // Name of new struct "type" double real; // member names double imagin; } Cmplx; double mag; // magnitude ch 6-4
Declare Structure Variable With structure type defined, now declare variables of this new type: Cmplx c1, c2; Just like declaring simple types Variable c1 and c2 are now of type Cmplx They contain "member values real, imagin, and mag Each of the struct "parts" ch 6-5
Accessing Structure Members Dot Operator to access members Cmplx c1; c1.real = 2.0; c1.imagin = 3.0; c1.mag = sqrt(pow(c1.real, 2.0) + pow(c1.imagin, 2.0) ); Called "member variables" The "parts (attribute) of the structure variable Different structs can have same name member variables No conflicts struct Student { int st_id; char name[20]; Date birthdate; }; struct Employ { int emp_id; char name[20]; Date birthdate; }; ch 6-6
typedef struct MyCmplx { double real; double imagin; double mag; } Cmplx; void printcmplx(cmplx c) { char sign; Structure Example } sign = (c.imagin < 0)? '-' : '+'; cout << setw(8) << c.real <<" " << sign << " j" << fabs(c.imagin) ; cout << " (magnitude " << c.mag << ")" << endl; Cmplx cmplxadd(cmplx c1, Cmplx c2) { Cmplx res; res.real = c1.real + c2.real; res.imagin = c1.imagin + c2.imagin; res.mag = sqrt(res.real*res.real + res.imagin*res.imagin); return res; } ch 6-7
Cmplx cmplxsub(cmplx c1, Cmplx c2) { Cmplx res; res.real = c1.real - c2.real; res.imagin = c1.imagin - c2.imagin; res.mag = sqrt(res.real*res.real + res.imagin*res.imagin); return res; } Cmplx cmplxmultiply(cmplx c1, Cmplx c2) { Cmplx res; res.real = (c1.real * c2.real) - (c1.imagin * c2.imagin); res.imagin = (c1.real * c2.imagin) + (c1.imagin * c2.real); res.mag = sqrt(res.real*res.real + res.imagin*res.imagin); return res; } Cmplx cmplxdivide(cmplx c1, Cmplx c2) { Cmplx res; double denom; denom = c2.real*c2.real + c2.imagin*c2.imagin; res.real = ((c1.real * c2.real) + (c1.imagin * c2.imagin)) / denom; res.imagin = ((c2.real * c1.imagin) - (c1.real * c2.imagin)) / denom; res.mag = sqrt(res.real*res.real + res.imagin*res.imagin); return res; } ch 6-8
1. int main() 2. { 3. Cmplx cmplxs[7]; 4. cout << "Input two complex numbers : c1.real, c1.imagin, 5. cout << c2.real, c2.imagin"<<endl; 6. cout << "c1.real : "; 7. cin >> cmplxs[0].real; 8. cout << "c1.imagin : "; 9. cin >> cmplxs[0].imagin; 10. cmplxs[0].mag = sqrt((cmplxs[0].real*cmplxs[0].real) 11. + (cmplxs[0].imagin * cmplxs[0].imagin)); 12. cout << "c2.real : "; 13. cin >> cmplxs[1].real; 14. cout << "c2.imagin : "; 15. cin >> cmplxs[1].imagin; 16. cmplxs[1].mag = sqrt((cmplxs[1].real*cmplxs[1].real) 17. + (cmplxs[1].imagin * cmplxs[1].imagin)); ch 6-9
18. cmplxs[2] = cmplxadd(cmplxs[0], cmplxs[1]); 19. cmplxs[3] = cmplxsub(cmplxs[0], cmplxs[1]); 20. cmplxs[4] = cmplxmultiply(cmplxs[0], cmplxs[1]); 21. cmplxs[5] = cmplxdivide(cmplxs[0], cmplxs[1]); 22. cmplxs[6] = cmplxs[0]; 23. for (int i=0; i<7; i++) { 24. cout << "cmplxs[" << i << "]: "; 25. printcmplx(cmplxs[i]); 26. } 27. return 0; 28.} ch 6-10
Structure Assignments Given structure named Cmplx Declare two structure variables: Cmplx c1, c2; Both are variables of "struct type Cmplx" Simple assignments are legal: c2 = c1; Simply copies each member variable from c1 into member variables of c2 ch 6-11
Structures as Function Arguments Passed like any simple data type Pass-by-value Pass-by-reference Or combination Can also be returned by function Return-type is structure type Return statement in function definition sends structure variable back to caller ch 6-12
Initializing Structures Can initialize at declaration Example: struct Planet { }; char name[10]; double relativemass; double distance; struct Planet earth = { Earth, 1.0, 150}; Declaration provides initial data to all three member variables ch 6-13
Array of Structure Struct data elements can be organized in array Example) struct Planet solarsystem[solar_planets] = { {"Mercury", 0.0558, 57.9}, {"Venus", 0.815, 108}, {"Earth",1.0, 150}, {"Mars", 0.107, 228}, {"Jupiter", 318, 778}, {"Saturn", 95.1, 1430}, {"Uranus", 14.5, 2870}, {"Neptune", 17.2, 4500}, {"Pluto", 0.11, 5900} }; ch 6-14
Handling attributes of each element of struct array void printplanets(struct Planet solarplanets[], int num_planet) 1. { 2. cout.setf(ios::fixed); 3. cout.setf(ios::showpoint); 4. for (int i=0; i<num_planet; i++) { 5. cout << setw(2) << i; 6. cout << " Name: "; 7. cout << setiosflags(ios::left) <<setw(8) << solarplanets[i].name; 8. cout << resetiosflags(ios::left); 9. cout << " Rel Mass: "; 10. cout << setw(7) << setprecision(3) <<solarplanets[i].relativemass; 11. cout << " Dist from Sun: "; 12. cout << setw(6) << setprecision(1) << solarplanets[i].distance ; 13. cout << endl; 14. } // end for 15.} ch 6-15
Sorting Array of Structure Sorting elements in array of structure (1) void sortplanetsbyrelmass(struct Planet solarplanets[], int num_planet) 1. { 2. struct Planet temp; 3. int i, j, m; 4. double min_relmass; 5. for (i=0; i<num_planet-1; i++) { 6. m = i; 7. min_relmass = solarplanets[i].relativemass; 8. for (j=i+1; j<num_planet; j++) { 9. if (min_relmass > solarplanets[j].relativemass) { 10. m = j; 11. min_relmass = solarplanets[j].relativemass; 12. } 13. } // end inner for 14. if (m!= i) { // if new minimum found, swap 15. temp = solarplanets[i]; 16. solarplanets[i] = solarplanets[m]; 17. solarplanets[m] = temp; 18. } 19. } // end outer for 20. } ch 6-16
Sorting elements in array of structure (2) void sortplanetsbyname(struct Planet solarplanets[], int num_planet) { 1. struct Planet temp; 2. int i, j, m; 3. char min_name[10] = {0}; 4. for (i=0; i<num_planet-1; i++) { 5. m = i; 6. strcpy(min_name, solarplanets[i].name); 7. for (j=i+1; j<num_planet; j++) { 8. if (strcmp(min_name, solarplanets[j].name) > 0) { 9. m = j; 10. strcpy(min_name, solarplanets[j].name); 11. } 12. } // end inner for 13. if (m!= i) { // if new minimum found, swap 14. temp = solarplanets[i]; 15. solarplanets[i] = solarplanets[m]; 16. solarplanets[m] = temp; 17. } 18. } // end outer for 19.} ch 6-17
1. int main() { 2. struct Planet solarsystem[solar_planets] = 3. {{"Mercury", 0.0558, 57.9}, {"Venus", 0.815, 108}, {"Earth",1.0, 150}, 4. {"Mars", 0.107, 228}, {"Jupiter", 318, 778}, {"Saturn", 95.1, 1430}, 5. {"Uranus", 14.5, 2870}, {"Neptune", 17.2, 4500}, {"Pluto", 0.11, 5900} }; 6. cout << "Initial state" << endl; 7. printplanets(solarsystem, SOLAR_PLANETS); 8. sortplanetsbyrelmass(solarsystem, SOLAR_PLANETS); 9. cout << "\ nafter sorting by relative mass:" << endl; 10. printplanets(solarsystem, SOLAR_PLANETS); 11. sortplanetsbydist(solarsystem, SOLAR_PLANETS); 12. cout << "\ nafter sorting by distance from sun:" << endl; 13. printplanets(solarsystem, SOLAR_PLANETS); 14. sortplanetsbyname(solarsystem, SOLAR_PLANETS); 15. cout << "\ nafter sorting by name using strcmp and strcpy:" << endl; 16. printplanets(solarsystem, SOLAR_PLANETS); 17. cout << "\ n\ n"; 18. 19. return 0; 20.} ch 6-18
result of execution ch 6-19
Example of struct typedef struct MyDayOfYear { int year; int month; int day; }DayOfYear; DayOfYear dy1, dy2; dy1.year = 2013; dy1.month = 9; dy1.day = 2; Struct DayOfYear dy2.year = -999; // no compilation error; but is this logically correct? dy2.month = 500; // no compilation error; but is this logically correct? dy2.day = -45; // no compilation error; but is this logically correct? ch 6-20
Limitations of struct the data members in a struct variable can be accessed by any function if the address of the struct variable is known no member function that checks the correctness (validness) of the data ch 6-21
Similar to structures Classes Not only, just member data But also, adds member functions Integral to object-oriented programming Focus on objects Object: Contains data and operations Class: mold ( 주형형틀, 거푸집 ) or blue print to instantiate an object In C++, variables of class type are objects ch 6-22
Class Definitions Defined similar to structures Example: class DayOfYear name of new class type { public: access specifier! void output(); member function! int month; int day; }; Notice only member function s prototype Function s implementation is elsewhere ch 6-23
Declaring Objects Declared same as all variables Predefined types, structure types Example: DayOfYear today, birthday; Declares two objects of class type DayOfYear Objects include: Data Members: month, day Operations (member functions) output() ch 6-24
Class Member Access Members accessed same as structures Example: today.month today.day And to access member function: today.output(); Invokes member function ch 6-25
Class Member Functions Must define or "implement" class member functions Like other function definitions Can be after main() definition Must specify class: void DayOfYear::output() { } :: is scope resolution operator Instructs compiler "what class" member is from Item before :: called type qualifier ch 6-26
Class Member Functions Definition Notice output() member function s definition (in next example) Refers to member data of class No qualifiers Function used for all objects of the class Will refer to "that object s" data when invoked Example: today.output(); Displays "today" object s data ch 6-27
Complete Class Example: Display 6.3 Class With a Member Function (1 of 4) ch 6-28
Display 6.3 Class With a Member Function (2 of 4) ch 6-29
Display 6.3 Class With a Member Function (3 of 4) ch 6-30
Display 6.3 Class With a Member Function (4 of 4) ch 6-31
Dot and Scope Resolution Operator Used to specify "of what thing" they are members Dot operator: Specifies member of particular object Scope resolution operator (::) Specifies what class the function definition comes from ch 6-32
A Class s Place Class is full-fledged type! Just like data types int, double, etc. Can have variables of a class type We simply call them "objects" Can have parameters of a class type Pass-by-value Pass-by-reference Can use class type like any other type! ch 6-33
Encapsulation Any data type includes Data (range of data) Operations (that can be performed on data) Example: int data type has: Data: - 2 31 ~ + 2 31 Operations: +,-,*,/,%, logical, etc. Same with classes But WE specify data, and the operations to be allowed on our data! ch 6-34
Abstract Data Type (ADT) "Abstract" Programmers don t know details Abbreviated "ADT" Collection of data values together with set of basic operations defined for the values ADT s often "language-independent" We implement ADT s in C++ with classes C++ class "defines" the ADT Other languages implement ADT s as well ch 6-35
Encapsulation Encapsulation Means "bringing together as one" Declare a class get an object Object is "encapsulation" of Data values Operations on the data (member functions) ch 6-36
Information Hiding Principles of OOP Details of its implementations and its operations work not known to "user" of the class enhances the adaptability of new technology Data Abstraction Details of how data is manipulated within ADT/class not known to user Encapsulation Bring together data and operations, but keep "details" hidden ch 6-37
Encapsulation in Object Encapsulation and protection of private data Object outside program interface to outside Friend Functions - cin >> // standard input - cout << // standard output Public Member Functions - get() // read with validity check - set() // write with validity check Private Member Functions - house keeping Private Data Members ch 6-38
Public and Private Members Data in class almost always designated private in definition! Upholds principles of OOP Hide data from user Allow manipulation only via operations Which are member functions Public items (usually member functions) are "user-accessible" ch 6-39
Public and Private Example Modify previous example: class DayOfYear { public: void input(); void output(); private: int month; int day; }; Data now private Objects have no direct access ch 6-40
Public and Private Example 2 Given previous example Declare object: DayOfYear today; Object today can ONLY access public members cin >> today.month; // NOT ALLOWED! cout << today.day; // NOT ALLOWED! Must instead call public operations: today.input(); today.output(); ch 6-41
Public and Private Style Can mix & match public & private More typically place public first Allows easy viewing of portions that can be USED by programmers using the class Private data is "hidden", so irrelevant to users Outside of class definition, cannot change (or even access) private data ch 6-42
Accessor and Mutator Functions Object needs to "do something" with its data Call accessor member functions Allow object to read data Also called "get member functions" Simple retrieval of member data Mutator member functions Allow object to change data Manipulated based on application Set member functions ch 6-43
// Display 6.4 Class with Private Members #include <iostream> #include <cstdlib> using namespace std; class DayOfYear { public: void input( ); void output( ); void set(int newmonth, int newday); //Precondition: newmonth and newday form a possible date. void set(int newmonth); //Precondition: 1 <= newmonth <= 12 //Postcondition: The date is set to the first day of the given month. int getmonthnumber( ); //Returns 1 for January, 2 for February, etc. int getday( ); private: int month; int day; }; ch 6-44
int main( ) { DayOfYear today, bachbirthday; cout << "Enter today's date:\ n"; today.input( ); cout << "Today's date is "; today.output( ); cout << endl; bachbirthday.set(3, 21); cout << "J. S. Bach's birthday is "; bachbirthday.output( ); cout << endl; if ( today.getmonthnumber( ) == bachbirthday.getmonthnumber( ) && today.getday( ) == bachbirthday.getday( ) ) cout << "Happy Birthday Johann Sebastian!\ n"; else cout << "Happy Unbirthday Johann Sebastian!\ n"; } return 0; ch 6-45
//Uses iostream and cstdlib: void DayOfYear::set(int newmonth, int newday) { if ((newmonth >= 1) && (newmonth <= 12)) month = newmonth; else { cout << "Illegal month value! Program aborted.\ n"; exit(1); } if ((newday >= 1) && (newday <= 31)) day = newday; else { cout << "Illegal day value! Program aborted.\ n"; } } exit(1); //Uses iostream and cstdlib: void DayOfYear::set(int newmonth) { if ((newmonth >= 1) && (newmonth <= 12)) month = newmonth; else { cout << "Illegal month value! Program aborted.\ n"; } exit(1); } day = 1; ch 6-46
int DayOfYear::getMonthNumber( ) { return month; } int DayOfYear::getDay( ) { return day; } //Uses iostream and cstdlib: void DayOfYear::input( ) { cout << "Enter the month as a number: "; cin >> month; cout << "Enter the day of the month: "; cin >> day; if ((month < 1) (month > 12) (day < 1) (day > 31)) { cout << "Illegal date! Program aborted.\ n"; exit(1); } } ch 6-47
void DayOfYear::output( ) { switch (month) { case 1: cout << "January "; break; case 2: cout << "February "; break; case 3: cout << "March "; break; case 4: cout << "April "; break; case 5: cout << "May "; break; case 6: cout << "June "; break; case 7: cout << "July "; break; case 8: cout << "August "; break; case 9: cout << "September "; break; case 10: cout << "October "; break; case 11: cout << "November "; break; case 12: cout << "December "; break; default: cout << "Error in DayOfYear::output. Contact software vendor."; } // end switch } cout << day; ch 6-48
Separation of Interface and Implementation User of class need not see details of how class is implemented Principle of OOP encapsulation User only needs "rules" Called "interface" for the class In C++ public member functions and associated comments Implementation of class is hidden Member function definitions elsewhere User need not see them ch 6-49
Structures vs. Classes Structures Typically all members public No member functions Classes Typically all data members private Interface member functions public Technically, same Perceptionally, very different mechanisms ch 6-50
Thinking Objects Focus for programming changes Before algorithms center stage Object-Oriented Programming (OOP) data is focus Algorithms still exist They simply focus on their data Are "made" to "fit" the data Designing software solution Define variety of objects and how they interact ch 6-51
Summary 6-1 Structure is collection of different types Class used to combine data and functions into single unit -> object Member variables and member functions Can be public accessed outside class Can be private accessed only in a member function s definition Class and structure types can be formal parameters to functions ch 6-52
Summary 6-2 C++ class definition Should separate two key parts Interface: what user needs Implementation: details of how class works ch 6-53
6.1 Key ideas Homework 6 (1) C++ Object-Oriented programming 에서 encapsulation 이란무슨의미인가? Encapsulation 을함으로써어떤장점이있는가? (2) C++ Object-Oriented programming 에서 information hiding 이란무슨의미인가? 무엇을누구에게숨기는것인가? 6.2 Programming project 6-5. (class Fraction) 6.3 Programming project 6-8. (class Money) 6.4 Programming project 6-10. (class Temperature) ch 6-54