86
611 18200 計計計計計計計 Lecture 11-1 計計計計計計計計計計計 1 1 Class Functions and Conversions

Class Functions and Conversions

  • Upload
    luka

  • View
    48

  • Download
    0

Embed Size (px)

DESCRIPTION

11. Class Functions and Conversions. Contents. Assignment Additional class features Operator functions Data type conversions Random numbers and simulations Class inheritance Polymorphism Common programming errors. Assignment. - PowerPoint PPT Presentation

Citation preview

Page 1: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-1 國立臺灣大學生物機電系

11Class Functions and

Conversions

Page 2: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-2 國立臺灣大學生物機電系

Contents

• Assignment• Additional class features• Operator functions• Data type conversions• Random numbers and simulations• Class inheritance• Polymorphism• Common programming errors

Page 3: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-3 國立臺灣大學生物機電系

Assignment

• Memberwise assignment: Allows assignment of data member values of an object to their counterparts in another object of the class– Compiler builds this type of default assignment if

there are no instructions to the contrary• Assignment operators:

– Declared in class declaration section– Defined in class implementation section– Example: a = b; in main() of Program 13.1

Page 4: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-4 國立臺灣大學生物機電系

AssignmentProgram 11.1: Assignment Example: Declaration

#include <iostream>#include <iomanip>using namespace std;// class declarationclass Date{ private: int month; int day; int year; public: Date(int = 7, int = 4, int = 2005); // constructor prototype void showDate(); // member function to display a Date

};

Page 5: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-5 國立臺灣大學生物機電系

AssignmentProgram 11.1: Assignment Example: Implementation

// implementation sectionDate::Date(int mm, int dd, int yyyy){ month = mm; day = dd; year = yyyy;}void Date::showDate(){ cout << setfill ('0') << setw(2) << month << '/' << setw(2) << day << '/' << setw(2) << year % 100; return;}

Page 6: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-6 國立臺灣大學生物機電系

AssignmentProgram 11.1: Assignment Example: main()

int main(){ Date a(4,1,1999), b(12,18,2006); // declare two

// objects cout << "\nThe date stored in a is originally "; a.showDate(); // display the original date a = b; // assign b's value to a cout << "\nAfter assignment the date stored in a is "; a.showDate(); // display a's values cout << endl; return 0;}

Page 7: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-7 國立臺灣大學生物機電系

Assignment

• Assignment operator declaration:– Format: void operator=(Date& );

• Declares simple assignment operator for Date class of Program 11.1

• Add to public section of class declarations– Keyword void: Assignment returns no value– operator= indicates overloading of assignment

operator with new version– (className& ): Argument to operator is class

reference

Page 8: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-8 國立臺灣大學生物機電系

Assignment• Assignment operator implementation format:

void Date::operator=(Date& newdate){ day = newdate.day; // assign the day month = newdate.month; // assign the month year = newdate.year; // assign the year}

• Add to implementation section of Program 11.1– newdate: a reference to the Date class

• Reference parameters facilitate overloaded operators– day, month, and year members of newdate:

Assigned to corresponding members of current object

Page 9: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-9 國立臺灣大學生物機電系

Assignment

• Program 11.2: Program 11.1 + declaration and implementation of overloaded assignment operator (operator=)

• Allows for assignments such as: a.operator= (b);

– Calls overloaded assignment operator to assign b’s members to a

• a.operator = (b) can be replaced with a = b;

Page 10: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-10 國立臺灣大學生物機電系

Assignment

• Other issues affecting assignment operators– Use constant reference parameter

• Format: void Date::operator=(const Date& secdate);

• Precludes inadvertent change to secdate– Assignment returns no value

• Cannot be used in multiple assignments such as:a = b = c

• Reason: a = b = c equivalent to a = (b = c)– But (b = c) returns no value making assignment to a

an error

Page 11: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-11 國立臺灣大學生物機電系

Copy Constructors

• Copy constructor: Initializes an object using another object of same class– Example: Two equivalent formats

Date b = a;Date b(a);

• Default copy constructor: Constructed by compiler if none declared by programmer– Similar to default assignment constructor– Performs memberwise copy between objects– Does not work well with pointer data members

Page 12: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-12 國立臺灣大學生物機電系

Copy Constructors

• Format: className(const className&);

– Function name must be class name– Parameter is reference to class– Parameter specified as const to prevent

inadvertent change• Declaration: Copy constructor for Date class

Date(const Date&);

Page 13: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-13 國立臺灣大學生物機電系

Copy Constructors

• Implementation: Copy constructor for Date class

Date::Date(const Date& olddate){ month = olddate.month; day = olddate.day; year = olddate.year;}

Page 14: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-14 國立臺灣大學生物機電系

Copy Constructors

Figure 11.1: Initialization and assignment

c = a;

Date c = a;Type definition Initialization

Assignment

Page 15: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-15 國立臺灣大學生物機電系

Base/Member Initialization

• Copy constructor does not perform true initialization– Creates and then assigns

• Base/Member initialization list: Initializes an object with no assignment– List can be applied only to constructor functions

Page 16: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-16 國立臺灣大學生物機電系

Base/Member Initialization

• Base/Member initialization list construction: Two methods– Construct list in class declaration section:

public: Date(int mo = 7, int da = 4, int yr = 2006): month(mo), day(da), year (yr) { }

Page 17: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-17 國立臺灣大學生物機電系

Base/Member Initialization

• Base/Member initialization list construction: Two methods (continued)– Declare prototype in declaration section, and

create list in implementation section// class declaration sectionpublic: Date(int = 7, int = 4, int = 2006); // prototype with defaults

// class implementation sectionDate::Date(int mo, int da, int yr) : month(mo), day(da),year(yr) {}

Page 18: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-18 國立臺灣大學生物機電系

Additional Class Features

• Additional features include: – Class scope– Static class members– Granting access privileges to nonmember

functions

Page 19: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-19 國立臺灣大學生物機電系

Class Scope

• The scope of a variable defines the portion of a program where the variable can be assessed

• Local variable scope is defined by any block inside a brace pair, {}

• Each class defines an associated class scope– Names of data and function members are local

to the scope of their class

Page 20: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-20 國立臺灣大學生物機電系

Class Scope

• Global variables can be assessed from their point of declaration throughout the remaining portion of the file containing them with three exceptions– If a local variable has the same name, the global

variable must be referenced with the scope resolution operator ::

– A global variable’s scope can be extended into another file via the extern keyword

– Same global name can be used in another file to define a separate variable via static keyword

Page 21: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-21 國立臺灣大學生物機電系

Class Scope

• If global variable name is reused in a class, the global variable is hidden by the class member

• Local variables hide the names of class data members having the same name

• Member function names can only be used by objects declared for the class

Page 22: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-22 國立臺灣大學生物機電系

Class Scope

• Example: scope of variables and functions

double rate; // global// class declarationclass Test{ private: double amount, price, total; // class scope public: double extend(double, double); // class scope }

Page 23: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-23 國立臺灣大學生物機電系

Figure 11.2 Example of scopes

Class Scope

double Test::extend(double amt, double pr){ amount = amt; price = pr; total = rate * amount * price;}

Global(file)

scope

Classscope

Local(block)scope

Global(file)

scope

Classscope

Classscope

Page 24: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-24 國立臺灣大學生物機電系

Static Class Members

• As each class object is created, it gets its own block of memory for its data members

• In some cases, it is convenient for every instantiation of a class to share the same memory location for a specific variable

Page 25: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-25 國立臺灣大學生物機電系

Figure 11.3 Sharing the static data member taxRate

Static Class Members

Page 26: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-26 國立臺灣大學生物機電系

Friend Functions

• Private variables can be accessed and manipulated through a class’s member functions

Figure 11.4a Direct access provided to member functions

Page 27: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-27 國立臺灣大學生物機電系

Friend Functions

• External access to private functions can be granted through the friends list mechanism

• The friends list members are granted the same privileges as a class’s member functions

• Nonmember functions in the list are called friend functions

• Friends list: Series of function prototype declarations preceded with the friend keyword

Page 28: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-28 國立臺灣大學生物機電系

Friend Functions Program 11.6#include <iostream>#include <cmath>using namespace std;// class declarationclass Complex{ // friends list friend double addreal(Complex&, Complex&); friend double addimag(Complex&, Complex&); private: double real; double imag; public: Complex(double = 0, double = 0); // constructor void display();};

Page 29: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-29 國立臺灣大學生物機電系

Friend Functions Program 11.6 (Continued)

// implementation section

Complex::Complex(double rl, double im){ real = rl; imag = im;}

void Complex::display(){ char sign = '+'; if(imag < 0) sign = '-'; cout << real << sign << abs(imag) << 'i'; return;}

Page 30: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-30 國立臺灣大學生物機電系

Friend Functions Program 11.6 (Continued)

// friend implementations

double addreal(Complex &a, Complex &b){ return(a.real + b.real);}

double addimag(Complex &a, Complex &b){ return(a.imag + b.imag);}

Page 31: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-31 國立臺灣大學生物機電系

Friend Functions Program 11.6 (Continued)int main(){ Complex a(3.2, 5.6), b(1.1, -8.4); double re, im; cout << "\nThe first complex number is "; a.display(); cout << "\nThe second complex number is "; b.display(); re = addreal(a,b); im = addimag(a,b); Complex c(re,im); // create a new Complex object cout << "\n\nThe sum of these two complex numbers is "; c.display(); cout << endl; return 0;}

Page 32: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-32 國立臺灣大學生物機電系

Operator Functions

• Only the symbols in Table 11.1 can be used for user-defined purposes

• New operator symbols cannot be created• Neither the precedence nor the associativity of

the C++ operators can be modified

Page 33: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-33 國立臺灣大學生物機電系

Operator Functions

• A user-defined operation is created as a function that redefines C++ built-in operator symbols for class use

• Functions that define operations on class objects and use C++ built-in operator symbols are operator functions

• Function name connects operator symbol to operation defined by function

• Operator function name has format operator<symbol>

Page 34: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-34 國立臺灣大學生物機電系

Operator Functions Program 11.8

#include <iostream> using namespace std;

// class declaration

class Date{ private: int month; int day; int year; public: Date(int = 7, int = 4, int = 2005); //constructor bool operator == (const Date &); // declare the operator== function};

Page 35: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-35 國立臺灣大學生物機電系

Operator Functions Program 11.8 (Continued)

// implementation sectionDate::Date(int mm, int dd, int yyyy){ month = mm; day = dd; year = yyyy;}bool Date::operator==(const Date &date2){ if(day == date2.day && month == date2.month && year == date2.year) return true; else return false;}

Page 36: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-36 國立臺灣大學生物機電系

Operator Functions Program 11.8 (Continued)

int main(){ // declare 3 objects Date a(4,1,2008), b(12,18,2001), c(4,1,2008); if (a == b) cout << "\nDates a and b are the same." << endl; else cout << "\nDates a and b are not the same." << endl;

if (a == c) cout << "Dates a and c are the same.\n" << endl; else cout << "Dates a and c are not the same.\n" << endl; return 0;}

Page 37: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-37 國立臺灣大學生物機電系

Operator Functions as Friends• Functions in Programs 11.7 and 11.8 constructed

as class members• All operator functions (except for =, (), [], ->)

may be written as friend functions• Example: operator+() function from Program

11.8– If written as friend, suitable prototype would be

friend Date operator+ (Date&, int);– Friend version contains reference to Date object

that is not contained in member version• Table 11.2: shows equivalence of functions and

arguments required

Page 38: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-38 國立臺灣大學生物機電系

Operator Functions as Friends

Table 11.2 Operator function argument requirements

Page 39: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-39 國立臺灣大學生物機電系

Operator Functions as Friends• Program 11.8’s operator+() function, written

as a friendDate operator+(Date& op1, int days){ Date temp; // a temporary Date to store the result

temp.day = op1.day + days; // add the days temp.month = op1.month; temp.year = op1.year; while (temp.day > 30) // now adjust the months { temp.month++; temp.day -= 30; } while (temp.month > 12) // adjust the years { temp.year++; temp.month -= 12; } return temp; // the values in temp are returned}

Page 40: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-40 國立臺灣大學生物機電系

Operator Functions as Friends

• Difference between the member and friend versions of operator+() function: Explicit use of additional Date parameter (op1)

• Convention for choosing between friend or member implementation:– Member function: Better for binary functions that

modify neither operand (such as ==, +, -)– Friend function: Better for binary functions that

modify one of their operands

Page 41: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-41 國立臺灣大學生物機電系

Operator Functions as Friends

• Most operator functions can be written as friend functions– Exceptions include =, (), [], and ->

• In all cases, the friend version of a member operator function must contain an additional class reference that the member function doesn’t require

Table 11.2 Operator Function Argument Requirements

Page 42: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-42 國立臺灣大學生物機電系

Data Type Conversions

• Conversion from one built-in data type to another discussed in Chapter 3

• Introduction of user-defined data types expands possibilities to following cases– Conversion from built-in type to built-in type– Conversion from built-in type to class (user-defined) type– Conversion from class (user-defined) type to built-in type– Conversion from class (user-defined) type to class (user-

defined) type

Page 43: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-43 國立臺灣大學生物機電系

Data Type Conversions

• Conversion from built-in to built-in:– Implicit conversion: Occurs in context of a C++

operation• Example: When double precision number is

assigned to integer variable, only integer portion stored

– Explicit conversion: Occurs when cast is used• Format dataType (expression)

Page 44: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-44 國立臺灣大學生物機電系

Data Type Conversions

• Conversion from built-in to class: Done using constructor functions– Type conversion constructor: Constructor

whose first argument is not member of its class and whose remaining arguments, if any, have default values

– If the first argument is built-in data type, the constructor can be used to cast built-in data type to class object

– Program 11.9 demonstrates this conversion type

Page 45: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-45 國立臺灣大學生物機電系

Data Type Conversions Program 11.9

#include <iostream> #include <iomanip>using namespace std;

// class declaration

class Date{ private: int month, day, year; public: Date(int = 7, int = 4, int = 2005); // constructor Date(long); // type conversion constructor void showDate();};

Page 46: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-46 國立臺灣大學生物機電系

Data Type Conversions Program 11.9 (Continued)

// implementation section// constructorDate::Date(int mm, int dd, int yyyy){ month = mm; day = dd; year = yyyy;}

// type conversion constructor from long to dateDate::Date(long findate){ year = int(findate/10000.0); month = int((findate - year * 10000.0)/100.0); day = int(findate - year * 10000.0 - month * 100.0);}

Page 47: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-47 國立臺灣大學生物機電系

Data Type Conversions Program 11.9 (Continued)

// member function to display a datevoid Date::showDate(){ cout << setfill('0') << setw(2) << month << '/' << setw(2) << day << '/' << setw(2) << year % 100;

return;}

Page 48: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-48 國立臺灣大學生物機電系

Data Type Conversions Program 11.9 (Continued)

int main(){ Date a, b(20101225L), c(4,1,1999); // declare 3 objects cout << "\nDates a, b, and c are "; a.showDate(); cout << ", "; b.showDate(); cout << ", and "; c.showDate(); cout << ".\n"; a = Date(20110103L); // cast a long to a date cout << "Date a is now "; a.showDate(); cout << ".\n\n"; return 0;}

Page 49: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-49 國立臺灣大學生物機電系

Data Type Conversions

• Conversion from class to built-in: Done by using:– Conversion operator function: Member

operator function that has name of built-in data type or class

– When operator function has built-in data type name, it is used to convert from class to built-in data type

– Usage of this type of function demonstrated in Program 11.10

Page 50: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-50 國立臺灣大學生物機電系

Data Type Conversions

• Conversion from class to class: Done using member conversion operator function– Same as cast from user-defined to built-in data

type– In this case, operator function uses class name

being converted to rather than built-in data name– Demonstrated in Program 11.11

Page 51: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-51 國立臺灣大學生物機電系

A Case Study: Random Numbers and Simulations

• Random numbers: Series of numbers whose order can’t be predicted

• Pseudorandom numbers: random enough for the type of applications being programmed

• All C++ compilers provide a rand() function for creating random numbers

Page 52: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-52 國立臺灣大學生物機電系

A Case Study: Random Numbers and Simulations Program 11.12#include <iostream>#include <ctime>#include <cmath>using namespace std;int main(){ double randValue; int i;

srand(time(NULL)); // this generates the first "seed" value for (i = 1; i <= 10; i++) { randValue = rand(); cout << randValue << endl; } return 0;}

Page 53: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-53 國立臺灣大學生物機電系

Scaling

• In most applications random numbers must be integers in a specified range

• Scaling is the procedure for adjusting random numbers produced by a random number generator to fall in a specified range

Page 54: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-54 國立臺灣大學生物機電系

Elevator Simulation

• Simulate an elevator’s operation• Output the current floor on which elevator is

stationed or passing by• Provide an internal elevator button to request

move to another floor• Elevator can travel between first and fifteenth

floor of building

Page 55: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-55 國立臺灣大學生物機電系

Class Inheritance

• Ability to create new classes from existing ones is the underlying motivation and power behind class- and object-oriented programming techniques

• Inheritance: – Deriving one class from another class

• Polymorphism: – Redefining how member functions of related

classes operate based on the class object being referenced

Page 56: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-56 國立臺灣大學生物機電系

Class Inheritance

• Base class: Initial class used as a basis for a derived class– Also called parent or superclass

• Derived class: New class incorporating all the data members and member functions of its base class– Also called child class or subclass– Can, and usually does, add its own data

members and member functions– Can override any base class function

Page 57: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-57 國立臺灣大學生物機電系

Class Inheritance

• Simple inheritance: Derived type has only one base type

• Multiple inheritance: Derived type has two or more base types

• Class hierarchies: Illustrate the hierarchy or order in which one class is derived from another

• Derived class has same form as any other class except: Includes access specifier and base class name

class derivedClassName : classAccess baseClassName

Page 58: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-58 國立臺灣大學生物機電系

Figure 11.6 Relating object types

Class Inheritance

Page 59: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-59 國立臺灣大學生物機電系

Figure 11.7 An example of multiple inheritance

Class Inheritance

car truck

minivan

Page 60: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-60 國立臺灣大學生物機電系

Class Inheritance

• Circle is the name of an existing class• Cylinder can be derived as shown below:

class Cylinder : public Circle{ // place any additional data members and // member functions in here // end of Cylinder class declaration}

Page 61: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-61 國立臺灣大學生物機電系

Access Specifications

• Until now we have used only private and public access specifiers within class

• private status ensures that data members can be accessed only by class member functions or friends– Prevents access by any nonclass functions (except

friends)– Also precludes access by any derived class

functions

Page 62: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-62 國立臺灣大學生物機電系

Access Specifications

• protected access: Third access specification permits only member or friend function access– Permits this restriction to be inherited by any

derived class – Derived class defines its inheritance subject to

base class’s access restrictions• Class-access specifier: Listed after colon at start

of its declaration section, defines inheritance• Table 11.3 lists inherited access restrictions

Page 63: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-63 國立臺灣大學生物機電系

Access Specifications

Table 11.3 Inherited Access Restrictions

Page 64: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-64 國立臺灣大學生物機電系

Access Specifications

Figure 11.8 Relationship between Circle and Cylinder data members

Page 65: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-65 國立臺灣大學生物機電系

Access Specifications

Figure 11.9 An assignment from derived to base class

Page 66: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-66 國立臺灣大學生物機電系

Access Specifications• Example: Derive Cylinder class from Circle class

// BASE class declarationclass Circle{ protected: double radius; public: Circle(double = 1.0); // constructor double calcval();};// class implementation// constructorCircle::Circle(double r) // constructor{ radius = r;}// calculate the area of a circledouble Circle::calcval(){ return(PI * radius * radius);}

Page 67: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-67 國立臺灣大學生物機電系

Access Specifications• Example: Derived Cylinder class

// class declaration where// Cylinder is derived from Circleclass Cylinder : public Circle{ protected: double length; // add one additional data member and public: // two additional function members Cylinder(double r = 1.0, double l = 1.0) : Circle(r),

length(l) {} double calcval();};// class implementationdouble Cylinder::calcval() // this calculates a volume

{ return (length * Circle::calcval()); // note the base

// function call}

Page 68: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-68 國立臺灣大學生物機電系

Access Specifications Program 11.14#include <iostream> #include <cmath>using namespace std;

// class declarationconst double PI = 2.0 * asin(1.0);class Circle{ protected: double radius; public: Circle(double = 1.0); // constructor double calcval();};

Page 69: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-69 國立臺灣大學生物機電系

Access Specifications Program 11.14 (Continued)

// implementation section for Circle

// constructorCircle::Circle(double r){ radius = r;}

// calculate the area of a circledouble Circle::calcval(){ return(PI * radius * radius);}

Page 70: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-70 國立臺灣大學生物機電系

Access Specifications Program 11.14 (Continued)

// class declaration for the derived class// Cylinder which is derived from Circleclass Cylinder : public Circle{ protected: double length; // add one additional data member and public: // two additional function members Cylinder(double r = 1.0, double l = 1.0) : Circle(r), length(l) {} double calcval();};

// implementation section for Cylinder

double Cylinder::calcval(void) // this calculates a volume{ return length * Circle::calcval(); // note the base function call}

Page 71: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-71 國立臺灣大學生物機電系

Access Specifications Program 11.14 (Continued)

int main(){ Circle circle_1, circle_2(2); // create two Circle objects Cylinder cylinder_1(3,4); // create one Cylinder object

cout << "\nThe area of circle_1 is " << circle_1.calcval() << endl; cout << "The area of circle_2 is " << circle_2.calcval() << endl; cout << "The volume of cylinder_1 is " << cylinder_1.calcval() << endl;

circle_1 = cylinder_1; // assign a cylinder to a Circle

cout << "\nThe area of circle_1 is now " << circle_1.calcval() << endl;

return 0;}

Page 72: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-72 國立臺灣大學生物機電系

Polymorphism

• Permits same function name to invoke one response in objects of base class and another response in objects of derived class– Example of polymorphism: Overriding of base

member function using an overloaded derived member function, as illustrated by the calcval() function in Program 11.14

• Function binding: Determines whether base class or derived class version of function will be used

Page 73: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-73 國立臺灣大學生物機電系

Polymorphism• Static binding: Determination of which function to

be called is made at compile time– Used in normal function calls

• Dynamic binding: Determination of which function to be called is made at run time (via virtual function)

• Virtual function (Example in Program 11.16): Creates pointer to function to be used– Value of pointer variable is not established until

function is actually called– At run time, and on the basis of the object making

the call, the appropriate function address is used

Page 74: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-74 國立臺灣大學生物機電系

Polymorphism Program 11.16#include <iostream> #include <cmath> using namespace std;

// class declaration for the base class

class One{ protected: double a; public: One(double = 2.0); // constructor virtual double f1(double); // a member function double f2(double); // another member function};

Page 75: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-75 國立臺灣大學生物機電系

Polymorphism Program 11.16 (Continued)

// class implementation for OneOne::One(double val) // constructor{ a = val;}double One::f1(double num) // a member function{ return(num/2);}double One::f2(double num) // another member function{ return( pow(f1(num),2) ); // square the result of f1()}

Page 76: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-76 國立臺灣大學生物機電系

Polymorphism Program 11.16 (Continued)

// class declaration for the derived classclass Two : public One{ public: virtual double f1(double); // this overrides class One's f1()};

// class implementation for Twodouble Two::f1(double num){ return(num/3);}

Page 77: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-77 國立臺灣大學生物機電系

Polymorphism Program 11.16 (Continued)

int main(){ One object_1; // object_1 is an object of the base class Two object_2; // object_2 is an object of the derived class

// call f2() using a base class object call cout << "The computed value using a base class object call is " << object_1.f2(12) << endl;

// call f2() using a derived class object call cout << "The computed value using a derived class object call is " << object_2.f2(12) << endl; return 0;}

Page 78: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-78 國立臺灣大學生物機電系

Figure 11.10 An inheritance diagram

Polymorphism

class A

class B

class C

Page 79: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-79 國立臺灣大學生物機電系

Common Programming Errors• Using user-defined operator in a multiple

assignment expression when operator does not return object

• Using keyword static when defining static data member or member function– Should only be used in declaration

• Using friend keyword with a function– Should only be used in declaration

• Failing to instantiate static data members before creating class objects that must access these data members

Page 80: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-80 國立臺灣大學生物機電系

Common Programming Errors

• Attempting to redefine operator’s meaning as applied to built-in data type

• Redefining overloaded operator to perform function not indicated by conventional meaning– Works but considered bad programming practice

• Attempting to make a conversion operator function a friend rather than member function

• Attempting to return type for conversion operator function

Page 81: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-81 國立臺灣大學生物機電系

Common Programming Errors

• Attempting to override virtual function without using same type and number of arguments as original

• Using keyword virtual in class implementation section– Functions declared as virtual only in declaration

section

Page 82: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-82 國立臺灣大學生物機電系

Summary

• Assignment operator can be declared for class as:void operator=(className&);

• Copy constructor initializes one object by using another object of the same class

className(const className&);• Each class has associated class scope defined by

brace pair {} containing class definition• Each class object has separate memory for members

except those declared static• Static function members apply to class as whole rather

than to separate objects

Page 83: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-83 國立臺灣大學生物機電系

Summary

• Non-member function can access class’s private data members if granted friend status

• User-defined operators can be constructed for classes by using operator functions

• User-defined operators can be called as a conventional function with arguments or as an operator function

• Operator functions can also be written as friend functions

Page 84: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-84 國立臺灣大學生物機電系

Summary

• Four categories of data type conversions– Built-in types to built-in types– Built-in types to class types– Class types to built-in types– Class types to class types

• Type conversion constructor: First argument is not a member of its class; any remaining arguments have default values

• Conversion operator function: Member function having the name of a class– No explicit arguments or return type

Page 85: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-85 國立臺灣大學生物機電系

Summary

• Inheritance: Capability of deriving one class from another class– Initial class used as basis for derived class:

base, parent, or superclass– Derived class: child or subclass

• Base class functions can be overridden by derived class functions with same name

• Polymorphism: Capability of having the same function name invoke different responses based on the object making the call

Page 86: Class Functions and Conversions

611 18200 計算機程式語言 Lecture 11-86 國立臺灣大學生物機電系

Summary

• Override functions and virtual functions can be used to implement polymorphism

• Static binding: Determination of which function is called is made at compile time

• Virtual binding: Dynamic binding should take place– Specification is made in function’s prototype by

placing the keyword virtual before the function’s return type

– After a function is declared virtual it remains virtual for all derived classes