Docstoc

09Chapter9

Document Sample
09Chapter9 Powered By Docstoc
					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
§9.1 Introduction
¡   Object-Oriented Programming (OOP)
    (面向对象编程)
    l   Programming using objects
¡   Object(对象)
    l   Represents an entity in the real world that can be
        distinctly identified. For example, a student, a desk, a
        circle, and even a loan.
    l   Has a unique identity, state, and behaviors.
         ¡   State: a set of data fields (or properties) with values
         ¡   Behavior: a set of functions



                                                                       2
Real World vs. Cyber World


     Problem    Abstraction          Computer
      Entity                         Program
                                    (Functions,
                                  Classes/Objects)
                materialization
     Solution

   Real world                      Cyber World




                                                     3
Objects and Class(类与对象)




   Circle objects


                     radius,
                    getArea()
    Circle class
                                4
Class
¡   The structure that defines objects of the same type.
¡   Variables:
    l   to define data fields (properties)
¡   Functions:
    l   to define behaviors




                                          radius,
                                         getArea()


                                                     5
    §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
                                                 6
UML Class Diagram




                    7
Constructor(构造函数)




¡   A special type of function to construct objects from
    the class
    l   Plays the role of initializing objects
    l   Exactly the same name as the class
    l   No return type—not even void
    l   Executed automatically by the system, NOT YOU!
                                                         8
Constructor
¡   Can be overloaded
    l   To construct objects with different initial data values
¡   No-arg constructor
    l   A constructor with no parameters
¡   Default constructor
    l   No parameters, empty body
    l   Provided automatically only if no explicitly declared
        constructors class Circle {
                     public:
                        double radius;
                        double getArea() {
                             return radius * radius * 3.14159; }
                     };                                       9
Creating Objects
¡   The syntax to create an object
      ClassName variableName;
    For example,
                                no-arg constructor
      Circle circle1;
      Circle a;
    A constructor is invoked when an object is created



                  Data type vs. Variable
                    Class vs. Object

                                                         10
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




                                           11
§9.3 Accessing Objects
¡   To access the members of a class/object
     l   Data fields and functions


    objectName.dataField
    --references a data field in the object.

    objectName.function(arguments)
    --invokes a function on the object.



                                               12
A Simple Circle Class
¡   Objective: demonstrate creating objects,
    accessing data, and using functions




               TestCircle         Run




                                               13
Memberwise Copy
¡   “=”: to copy the contents from one object to the
    other.
    l   By default, each data field of one object is copied to its
        counterpart in the other object. For example,


         circle2 = circle1;


                 radius:15                   radius:15
                                             radius:10
                 getArea()                   getArea()
                                             getArea()




                                                                14
Anonymous Object(匿名对象)
¡   Objects without name
    l   Occasionally, you may create an object and use it only
        once.
    ClassName();
    ClassName(arguements);

                                        No “()”!
        Circle circle1;
        Circle circle2(5.0);
        cout<<circle1.getArea();
        cout<<circle2.getArea();
        cout<<Circle().getArea();           “()”!
        cout<<Circle(100).getArea();
                                                            15
Accessing Object Members via Pointers
¡   Pointing to existing objects
          Circle circle1;
          Circle *pCircle = &circle1;
¡   Creating dynamic objects
       ClassName *pObject = new ClassName();
       ClassName *pObject = new ClassName;
¡   Access using “.” or “->”
    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;
                                                              16
§9.4 Separating Declaration from Implementation

¡   Similar to the definition of function
¡   Declaration(声明):
    l   In classname.h file, conventionally
    l   Simply lists all the data fields, constructor prototypes,
        and the function prototypes.
¡   Implementation(实现):
    l   In classname .cpp file, conventionally
    l   Implements the constructors and functions.



          Circle.h         Circle.cpp              Run

                                                                17
Inline Declaration(声明)
¡   Inline Declaration:
    l   A member function automatically becomes an inline
        function if it is implemented inside a class declaration.
class A {
public:
                           Inline function
  A() {
    // do something;
  }                             double A::f2()
                                      inline double
  double f1() {                 {         A::f2()
    // return a number            // return a number
  }                             }
  double f2();
};
                          Inline function
                         Regular function
                                                               18
§9.5 Data Encapsulation and Class Scope
¡   Public(公有)
    l   A visibility/accessibility keyword
    l   All the following data             class Circle {
                                           public:
        fields/functions are accessible
                                               Circle();
                                               double radius;
        outside the class                      Circle();
                                               Circle(double);
                                                double getArea();
                                                Circle(double);
        Not good!
                                                double getArea();
                                           private:
        -Data may be tampered!             }; double radius;
        -Class is difficult to maintain!   };

¡   Private(私有)                            int main(){
    l   All the following data               Circle circle1;
        fields/functions are NOT             circle1.radius=0;
        accessible outside the class         cout << circle1.radius;
                                             cout<<circle1.getArea()<<endl;
                                           }
                                                                       19
Getter and Setter
¡   For users/clients of a class to retrieve and modify
    a data field encapsulated by “private”
¡   Getter/Accessor
    l   A function usually named getXxx:
            returnType getPropertyName()
            bool isPropertyName()
¡   Setter/Mutator
    l   A function usually named setXxx, e.g.:

            void setPropertyName(dataType propertyValue)


                                                       20
Example: New Circle Class




Circle2.h   Circle2.cpp     Run

                                  21
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
                                                             22
The Scope of Variables
¡   Global variables: declared outside all functions
     l   Scope: from declaration to the end of the program.
¡   Local variables: defined inside functions
     l   Scope: from declaration to the end of its block (may not
         the end of the function!)

                                                    …
int max(int x, int y){   for (int i=0; i<10;i++){   {
  …                        …                            …
  int i=0;                 int j=0;                     int j=0;
  …                        …                            …
}                        }                          }
                                                    …



                                                                   23
The Scope of Data Fields
¡   Class scope:
    l   The data fields are accessible to all constructors and
        functions in the class.
¡   Hidden data field:
    l   The data field with the same name as a local variable
        inside a function
    l   The local variable takes precedence

          HideDataField                     Run
         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;
          }                                                      24
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) {       Circle::getThis() {
            this->radius = radius;                 return *this;
            (*this).radius = radius;      }
    }

    // Set a new radius
    void Circle::setRadius(double radius) {
            this->radius = (radius >= 0) ? radius : 0;
    }
                                                                   25
A Special Scenario
¡   Accessing the data fields of the objects of the
    same class
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));
   }
};                                                               26
§9.6 Class vs. Data Type
¡   Class is a Type
    l   You can also use class names to declare object names,
        like a primitive data type.
¡   Object name is a constant
    l   Once an object name is declared, it references to an
        object. It cannot be reassigned to reference another
        object.
¡   Class replaces “struct”         class Student
        struct Student              {
        {                           public:
          int id;                     int id;
          char firstName[30];         char firstName[30];
          char mi;                    char mi;
          char lastName[30];          char lastName[30];
        };                          };
                                                               27
  Passing Objects to Functions
You can pass objects by value or by reference.




                   PassObjectByValue         Run

                 PassObjectByReference       Run

                  PassObjectToPointer        Run
                                                   28
  Array of Objects
Circle circleArray[3] = {Circle(3), Circle(4),
Circle(5)};




                  TotalArea               Run




                                                 29
Object Data Field
¡   Class as data field type
    l   An object is a member of another object/class

     class Time{             class Action{
     private:                private:
        int hour;               Time time;
        int minute;          };
        int second;
     };

¡   Construction of member object
    l   A member object is not created/constructed on its
        declaration
    l   It is created when its owner object is created
                                                            30
Default Constructor of Object Data Field
¡   The default constructor is automatically invoked
¡   Compiling error, if default constructor is not
    available ->
    l   Due to the declaration of constructor with arg



                 DefaultConstructor1




                                                         31
 Constructor Initializer
                                              NoDefaultConstructor2
 ¡   Used by a constructor
 ¡   To initialize data fields of the class




class Time{                           class Action{
public:                               public:
   Time(int hr, int min, int sec) {      Action(int hr, int min, int sec)
   }                                       :time(hr, min, sec) {
private:                                 }
     int hour;                        private:
     int minute;                         Time time;
     int second;                      };
};                                                                      32
§9.7 Class Abstraction and Encapsulation
¡   Class Abstraction
    l   To separate class implementation from the use of the class
    l   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.
    l   The user of the class does not need to know how the class is
        implemented.




                                                                         33
Example: The Loan Class




 Loan.h Loan.cpp TestLoanClass   Run
                                       34
§9.8 The C++ “string” Class
¡   A C++ library class defined in <string>
¡   With more features than C-string functions




                                                 35
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);




                                                     36
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;



                                                       37
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




                                                              38
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)



                                                                 39
  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




                                                          40
  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


                                                   41
  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



                                                     42
  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++




                                                            43
String Operators




                   44
Summary
¡   Concept of class/object
¡   Declaration of class
    l   Class header file
¡   Construction of objects
    l   Object member
¡   Object as parameter
¡   Object pointer
¡   Access control: public vs. private
¡   Scope of class member




                                         45
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

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:0
posted:3/26/2014
language:English
pages:46