Download presentation
Presentation is loading. Please wait.
Published byPaul Carson Modified over 9 years ago
1
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
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
3 Real World vs. Cyber World Cyber World Real world Solution Problem Computer Program materialization Abstraction (Functions, Classes/Objects) Entity
4
4 Objects and Class (类与对象) Circle objects radius, getArea() Circle class
5
5 Class The structure that defines objects of the same type. Variables: to define data fields (properties) Functions: to define behaviors radius, getArea()
6
6 §9.2 Defining Classes and Objects class Name { public: data fields functions Name() private: data fields functions }; 1. Capitalize the initials of class name 2. No initial value when declaring data fields
7
7 UML Class Diagram
8
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
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
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. Variable Class vs. Object
11
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
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
13 A Simple Circle Class Objective: demonstrate creating objects, accessing data, and using functions TestCircle Run
14
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:10 getArea() radius:15 getArea() radius:15 getArea()
15
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
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 radius << endl; cout getArea() << endl;
17
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 Run Circle.cpp
18
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 function Regular function double A::f2() { // return a number } inline double A::f2() Inline function
19
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
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
21 Example: New Circle Class Circle2.h Run Circle2.cpp
22
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 class For example, all the following declarations are equivalent Preferred: one public and one private, public first
23
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
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 Run HideDataField 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
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; }
26
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
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
28 Passing Objects to Functions You can pass objects by value or by reference. Run PassObjectByValue PassObjectByReference Run PassObjectToPointer
29
29 Array of Objects Circle circleArray[3] = {Circle(3), Circle(4), Circle(5)}; Run TotalArea
30
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
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
32 Constructor Initializer Used by a constructor To initialize data fields of the class 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
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.
34
34 Example: The Loan Class TestLoanClassRunLoan.cppLoan.h
35
35 §9.8 The C++ “string” Class A C++ library class defined in With more features than C-string functions
36
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
37 Appending a String string s1("Welcome"); s1.append(" to C++"); // appends " to C++" to s1 cout << 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
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 s1 cout << s1 << endl; // s1 now becomes Dallas string s2("Welcome"); s2.assign("Dallas, Texas", 0, 5); // assigns "Dalla" to s2 cout << s2 << endl; // s2 now becomes Dalla string s3("Welcome"); s3.assign("Dallas, Texas", 5); // assigns "Dalla" to s3 cout << s3 << endl; // s3 now becomes Dalla string s4("Welcome"); s4.assign(4, 'G'); // assigns "GGGG" to s4 cout << s4 << endl; // s4 now becomes GGGG
39
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 c cout << s1.erase(2, 3) << endl; // s1 is now Weme s1.clear(); // s1 is now empty cout << s1.empty() << endl; // s1.empty returns 1 (means true)
40
40 Comparing Strings Often, 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 -2 cout << s2.compare(s1) << endl; // returns 2 cout << s1.compare("Welcome") << endl; // returns 0
41
41 Obtaining Substrings You 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 W cout << s1.substr(3) << endl; // returns come cout << s1.substr(3, 3) << endl; // returns com
42
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 3 cout << s1.find("co", 6) << endl; // returns -1 cout << s1.find('o') << endl; // returns 4 cout << s1.find('o', 6) << endl; // returns 9
43
43 Inserting and Replacing Strings Here 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 HTML string s2("AA"); s2.insert(1, 4, 'B'); cout << s2 << endl; // s2 becomes to ABBBBA string s3("Welcome to HTML"); s3.replace(11, 4, "C++"); cout << s3 << endl; // returns Welcome to C++
44
44 String Operators
45
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
46
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.