Upload
paul-carson
View
231
Download
0
Embed Size (px)
DESCRIPTION
3 Real World vs. Cyber World Cyber World Real world Solution Problem Computer Program materialization Abstraction (Functions, Classes/Objects) Entity
Citation preview
Chapter 9 Objects and Classes
§9.1 Introduction§9.2 Defining Classes and Objects§9.3 Access Objects§9.4 Separating Declaration from Implementation§9.5 Data Encapsulation and Class Scope§9.6 Class vs. Data Type§9.7 Class Abstraction and Encapsulation§9.8 The C++ string Class
2
§9.1 Introduction
Object-Oriented Programming (OOP)(面向对象编程) Programming using objects
Object(对象) Represents an entity in the real world that can be
distinctly identified. For example, a student, a desk, a circle, and even a loan.
Has a unique identity, state, and behaviors. State: a set of data fields (or properties) with values Behavior: a set of functions
3
Real World vs. Cyber World
Cyber WorldReal worldSolution
Problem Computer Program
materialization
Abstraction
(Functions,Classes/Objects)
Entity
4
Objects and Class(类与对象)
Circle objects
radius,getArea()
Circle class
5
Class
The structure that defines objects of the same type. Variables:
to define data fields (properties) Functions:
to define behaviors
radius,getArea()
6
§9.2 Defining Classes and Objects
class Name {public: data fields functions Name()private: data fields functions};
class Circle { public: // The radius of this circle double radius; // Construct a circle object Circle() { radius = 1; } // Construct a circle object Circle(double newRadius) { radius = newRadius; } // Return the area of this circle double getArea() { return radius * radius * 3.14159; } };
Data field
Function
Constructors
1. Capitalize the initials of class name
2. No initial value when declaring data fields
7
UML Class Diagram
Circle radius: double Circle() Circle(newRadius: double) getArea(): double
circle1: Circle radius: 10
Class name Data fields Constructors and Functions
circle2: Circle radius: 25
circle3: Circle radius: 125
UML Class Diagram
UML notation for objects
8
Constructor(构造函数)
A special type of function to construct objects from the class Plays the role of initializing objects Exactly the same name as the class No return type—not even void Executed automatically by the system, NOT YOU!
9
Constructor
Can be overloaded To construct objects with different initial data values
No-arg constructor A constructor with no parameters
Default constructor No parameters, empty body Provided automatically only if no explicitly declared
constructors class Circle { public: double radius; double getArea() { return radius * radius * 3.14159; } };
10
Creating Objects
The syntax to create an object ClassName variableName; For example, Circle circle1; Circle a;
A constructor is invoked when an object is created
no-arg constructor
Data type vs. VariableClass vs. Object
11
Constructing Objects with Arguments
ClassName variableName(arguments); For example,
Circle circle2(5.5); Circle b(11);
Invoking the Circle class’s constructor with a specified radius 5.5
12
§9.3 Accessing Objects
To access the members of a class/object Data fields and functions
objectName.dataField --references a data field in the object.
objectName.function(arguments) --invokes a function on the object.
13
A Simple Circle Class
Objective: demonstrate creating objects, accessing data, and using functions
TestCircle Run
14
Memberwise Copy
“=”: to copy the contents from one object to the other. By default, each data field of one object is copied to its
counterpart in the other object. For example,
circle2 = circle1;
radius:10getArea()
radius:15getArea()
radius:15getArea()
15
Anonymous Object(匿名对象) Objects without name
Occasionally, you may create an object and use it only once.
ClassName(); ClassName(arguements);
Circle circle1;Circle circle2(5.0);cout<<circle1.getArea();cout<<circle2.getArea();cout<<Circle().getArea();cout<<Circle(100).getArea();
No “()”!
“()”!
16
Accessing Object Members via Pointers
Pointing to existing objects
Creating dynamic objects
Access using “.” or “->”
Circle circle1;Circle *pCircle = &circle1;
ClassName *pObject = new ClassName();ClassName *pObject = new ClassName;
cout << "The radius is " << (*pCircle).radius << endl;cout << "The area is " << (*pCircle).getArea() << endl;(*pCircle).radius = 5.5;cout << "The radius is " << pCircle->radius << endl;cout << "The area is " << pCircle->getArea() << endl;
17
§9.4 Separating Declaration from Implementation
Similar to the definition of function Declaration(声明) :
In classname.h file, conventionally Simply lists all the data fields, constructor prototypes,
and the function prototypes. Implementation(实现) :
In classname .cpp file, conventionally Implements the constructors and functions.
Circle.h RunCircle.cpp
18
Inline Declaration(声明) Inline Declaration:
A member function automatically becomes an inline function if it is implemented inside a class declaration.
class A {public: A() { // do something; } double f1() { // return a number } double f2();};
Inline functionInline function
Regular function
double A::f2(){ // return a number}
inline double A::f2()
Inline function
19
§9.5 Data Encapsulation and Class Scope
Public(公有) A visibility/accessibility keyword All the following data
fields/functions are accessible outside the class
Private(私有) All the following data
fields/functions are NOT accessible outside the class
class Circle {public:
double radius;Circle();Circle(double);double getArea();
};
Not good!-Data may be tampered!-Class is difficult to maintain!
class Circle {public:
Circle();Circle(double);double getArea();
private:double radius;
};
int main(){ Circle circle1; circle1.radius=0; cout << circle1.radius; cout<<circle1.getArea()<<endl;}
20
Getter and Setter
For users/clients of a class to retrieve and modify a data field encapsulated by “private”
Getter/Accessor A function usually named getXxx:
Setter/Mutator A function usually named setXxx, e.g.:
returnType getPropertyName()bool isPropertyName()
void setPropertyName(dataType propertyValue)
21
Example: New Circle Class
Circle
-radius: double +Circle() +Circle(radius: double) +getRadius(): double +setRadius(radius: double): void +getArea(): double
The radius of this circle (default: 1.0). Constructs a default circle object. Constructs a circle object with the specified radius. Returns the radius of this circle. Sets a new radius for this circle. Returns the area of this circle.
The - sign indicates private modifier
Circle2.h RunCircle2.cpp
22
Note “public” and “private” can appear any times in any
order in a class Data fields and functions can be declared in any order
in a classFor example, all the following declarations are equivalent
class Circle { public: Circle(); Circle(double); private: double radius; public: double getArea(); double getRadius(); void setRadius(double); }; (a) (b)
class Circle { private: double radius; public: double getArea(); double getRadius(); void setRadius(double); public: Circle(); Circle(double); };
class Circle { public: Circle(); Circle(double); double getArea(); double getRadius(); void setRadius(double); private: double radius; };
(c)
Preferred: one public and one private, public first
23
The Scope of Variables
Global variables: declared outside all functions Scope: from declaration to the end of the program.
Local variables: defined inside functions Scope: from declaration to the end of its block (may not
the end of the function!)
int max(int x, int y){ … int i=0; …}
for (int i=0; i<10;i++){ … int j=0; …}
…{ … int j=0; …}…
24
The Scope of Data Fields
Class scope: The data fields are accessible to all constructors and
functions in the class. Hidden data field:
The data field with the same name as a local variable inside a function
The local variable takes precedence
RunHideDataField void p() { int x = 20; // local variable cout << "x is " << x << endl; cout << "x of class is " << Foo::x << endl; cout << "y is " << y << endl; }
25
The “this” Pointer A special built-in pointer that points to the current object Used to cope with hidden data fields
// Construct a circle object Circle::Circle(double radius) {
this->radius = radius; (*this).radius = radius;
}
// Set a new radius void Circle::setRadius(double radius) {
this->radius = (radius >= 0) ? radius : 0; }
Circle::getThis() { return *this;
}
A Special Scenario
Accessing the data fields of the objects of the same class
26
class MyPoint{ private: double x, y; public: MyPoint(); MyPoint(double x, double y; double getX(); double getY(); double distance(const MyPoint point){ sqrt((x-point.x)*(x-point.x)+ (y-point.y)* (y-point.y)); }};
27
§9.6 Class vs. Data Type
Class is a Type You can also use class names to declare object names,
like a primitive data type. Object name is a constant
Once an object name is declared, it references to an object. It cannot be reassigned to reference another object.
Class replaces “struct”struct Student{ int id; char firstName[30]; char mi; char lastName[30];};
class Student{public: int id; char firstName[30]; char mi; char lastName[30];};
28
Passing Objects to Functions You can pass objects by value or by reference.
Run
RunPassObjectByValue
PassObjectByReference
RunPassObjectToPointer
c: Circle
radius: 5.0
myCircle: Circle radius: 5.0
Copy myCircle to c myCircle: Circle
radius: 5.0
c is an alias for myCircle
myCircle: Circle radius: 5.0
c:
address of myCircle
29
Array of Objects
Circle circleArray[3] = {Circle(3), Circle(4), Circle(5)};
RunTotalArea
30
Object Data Field Class as data field type
An object is a member of another object/class
Construction of member object A member object is not created/constructed on its
declaration It is created when its owner object is created
class Time{private:
int hour; int minute; int second;
};
class Action{private: Time time;};
31
Default Constructor of Object Data Field
The default constructor is automatically invoked Compiling error, if default constructor is not
available -> Due to the declaration of constructor with arg
DefaultConstructor1
32
Constructor Initializer Used by a constructor To initialize data fields of the class
Circle::Circle() : radius(1) { }
Circle::Circle() { radius = 1; }
Same as
(a)
(b) class Time{
public: Time(int hr, int min, int sec) { } private:
int hour; int minute; int second;
};
class Action{public: Action(int hr, int min, int sec) :time(hr, min, sec) { } private: Time time;};
NoDefaultConstructor2
33
§9.7 Class Abstraction and Encapsulation
Class Abstraction To separate class implementation from the use of the class The creator of the class provides a description of the class and let
the user know how the class can be used. The detail of implementation is encapsulated and hidden
from the user. The user of the class does not need to know how the class is
implemented.
Class Contract (Signatures of
public methods and public constants)
Class
Class implementation is like a black box hidden from the clients
Clients use the
class through the contract of the class
34
Example: The Loan Class
TestLoanClass RunLoan.cpp
Loan
-annualInterestRate: double -numberOfYears: int -loanAmount: double +Loan() +Loan(annualInterestRate: double,
numberOfYears: int, loanAmount: double)
+getAnnualInterestRate(): double +getNumberOfYears(): int +getLoanAmount(): double +setAnnualInterestRate( annualInterestRate: double): void +setNumberOfYears( numberOfYears: int): void +setLoanAmount( loanAmount: double): void +getMonthlyPayment(): double +getTotalPayment(): double
The annual interest rate of the loan (default: 2.5). The number of years for the loan (default: 1) The loan amount (default: 1000). Constructs a default Loan object. Constructs a loan with specified interest rate, years, and
loan amount. Returns the annual interest rate of this loan. Returns the number of the years of this loan. Returns the amount of this loan. Sets a new annual interest rate to this loan.
Sets a new number of years to this loan. Sets a new amount to this loan. Returns the monthly payment of this loan. Returns the total payment of this loan.
Loan.h
35
§9.8 The C++ “string” Class A C++ library class defined in <string> With more features than C-string functions
36
Constructing a String
A string object with empty string:
string newString;
A string object from a string literal or an char array: string newString(stringLiteral);
37
Appending a String
string s1("Welcome");s1.append(" to C++"); // appends " to C++" to s1cout << s1 << endl; // s1 now becomes Welcome to C++string s2("Welcome");s2.append(" to C and C++", 0, 5); cout << s2 << endl; string s3("Welcome");s3.append(" to C and C++", 5); cout << s3 << endl; string s4("Welcome"); s4.append(4, 'G'); cout << s4 << endl;
38
Assigning a String
You can use several overloaded functions to assign new contents to a string. For example, see the following code:
string s1("Welcome");s1.assign("Dallas"); // assigns "Dallas" to s1cout << s1 << endl; // s1 now becomes Dallasstring s2("Welcome");s2.assign("Dallas, Texas", 0, 5); // assigns "Dalla" to s2cout << s2 << endl; // s2 now becomes Dallastring s3("Welcome");s3.assign("Dallas, Texas", 5); // assigns "Dalla" to s3cout << s3 << endl; // s3 now becomes Dallastring s4("Welcome");s4.assign(4, 'G'); // assigns "GGGG" to s4cout << s4 << endl; // s4 now becomes GGGG
39
Functions at, clear, erase, and empty
You can use the at(index) function to retrieve a character at a specified index, clear() to clear the string, erase(index, n) to delete part of the string, and empty() to test if a string is empty. For example, see the following code:
string s1("Welcome");cout << s1.at(3) << endl; // s1.at(3) returns ccout << s1.erase(2, 3) << endl; // s1 is now Wemes1.clear(); // s1 is now emptycout << s1.empty() << endl; // s1.empty returns 1 (means true)
40
Comparing StringsOften, in a program, you need to compare the contents of two strings. You can use the compare function. This function works in the same way as the C-string strcmp function and returns a value greater than 0, 0, or less than 0. For example, see the following code:
string s1("Welcome");string s2("Welcomg");cout << s1.compare(s2) << endl; // returns -2cout << s2.compare(s1) << endl; // returns 2cout << s1.compare("Welcome") << endl; // returns 0
41
Obtaining SubstringsYou can obtain a single character from a string using the at function. You can also obtain a substring from a string using the substr function. For example, see the following code:
string s1("Welcome");cout << s1.substr(0, 1) << endl; // returns Wcout << s1.substr(3) << endl; // returns comecout << s1.substr(3, 3) << endl; // returns com
42
Searching in a String You can use the find function to search for a substring or a character in a string. For example, see the following code:
string s1("Welcome to HTML");cout << s1.find("co") << endl; // returns 3cout << s1.find("co", 6) << endl; // returns -1cout << s1.find('o') << endl; // returns 4cout << s1.find('o', 6) << endl; // returns 9
43
Inserting and Replacing StringsHere are the examples to use the insert and replace functions:
string s1("Welcome to HTML");s1.insert(11, "C++ and ");cout << s1 << endl; // s1 becomes Welcome to C++ and HTMLstring s2("AA");s2.insert(1, 4, 'B');cout << s2 << endl; // s2 becomes to ABBBBAstring s3("Welcome to HTML");s3.replace(11, 4, "C++");cout << s3 << endl; // returns Welcome to C++
44
String Operators
Operator Description [] Accesses characters using the array subscript operators.
= Copies the contents of one string to the other.
+ Concatenates two strings into a new string.
+= Appends the contents of one string to the other.
<< Inserts a string to a stream
>> Extracts characters from a stream to a string delimited by a
whitespace or the null terminator character.
==, !=, <, Six relational operators for comparing strings.
<=, >, >=
45
Summary Concept of class/object Declaration of class
Class header file Construction of objects
Object member Object as parameter Object pointer Access control: public vs. private Scope of class member
Homework Questions
1. What are the difference between constructors and member functions?
2. Design and implement a simple class as you want, with constructors and member functions.
3. What is the purpose of using accessibility control?
4. What are the benefits of data field encapsulation?
46