Beruflich Dokumente
Kultur Dokumente
16
17
Data Abstraction
The separation of the logical properties of a data
18
19
ADT Example
TYPE Time DOMAIN Each Time value is a time in hours, minutes, and seconds. OPERATIONS Set the time Print the time Increment by one second Compare 2 times for equality Determine if one time is less than another
20
21
4/3/2013
22
23
C++ Classes
A class is a structured type in C++ to implement
24
25
C++ Classes
Syntax:
class ClassName { private: DataMemberList; MethodMemberList1; public: MethodMemberList2; };
clients
26
27
public : void void void bool bool private : int int int }; hrs; mins; secs;
data members, use const in both the function prototype and the heading of the function definition
secs);
mins , int
26
4/3/2013
28
29
C++ Classes
A class usually has two types of members Data fields (member variables) Methods (member functions) Data fields should always be private Methods can be private or public
{ //begin of class private: //only accessible within this class int id; string firstName; string lastName; Member variables char gender; string major; float gpa; public: //accessible outside of this class int GetID ( ) { ... } void SetID ( int id ) Member { ... } ... }; //end of class
(similar to a struct)
functions
30
31
Class Objects
Facilitates re-use of C++ code for an ADT Software that uses the class is called a client Variables of the class type are called objects or
instances Client code uses classs public member functions to manipulate class objects
32
33
For Example
class Student // Student is a new data type! { private: int id; string firstName; ... }; Student stu1;
// instantiate an object stu1 in Student class // stu1 is an object (instance) of the Student class.
Exercise 1
Construct a class named Rectangle that has data
Perimeter() and Area() to calculate a rectangles perimeter and area, and a member method named SetSize() to set a rectangles length and width, and a member method named ShowData() that displays a rectangles length, width, perimeter, and area
4/3/2013
34
35
Exercise 2
Define a class called Employee Attributes? Methods?
class Employee { private: int id; string name; float payRate; float hours; float wages; public: void SetEmp(int idnum, string fullname, float rate, float hr) { id = idnum; .. } void CalcSalary() { wages = payRate * hours; } void PrintPayCheck () { cout << Employee ID: << id << endl << Name: << name << .; } };
Employee Class
36
37
function members
Header files iostream and fstream declare the istream, ostream,and
cin.get (someChar);
The following statements declare myInfile as an instance of class
ifstream and invoke function member called open ifstream myInfile; myInfile.open (mydata.dat);
38
41
Information Hiding
Information hiding - Class implementation details are
client code
specification
implementation
<< endl
4/3/2013
42
43
Method Calls
void main() { Student stu1; ... stu1.PrintStudentRecord(); ... return 0; }