xiaoyan li, 2007 1 csc211 data structures lecture 3 adt and c++ classes (ii) instructor: prof....
TRANSCRIPT
Xiaoyan Li, 2007Xiaoyan Li, 2007 11
CSC211 Data Structures CSC211 Data Structures
Lecture 3Lecture 3ADT and C++ Classes (II)ADT and C++ Classes (II)
Instructor: Prof. Xiaoyan LiInstructor: Prof. Xiaoyan LiDepartment of Computer Science Department of Computer Science
Mount Holyoke CollegeMount Holyoke College
Xiaoyan Li, 2007Xiaoyan Li, 2007 22
OutlineOutline
A Review of C++ Classes (Lecture 2)A Review of C++ Classes (Lecture 2) OOP, ADTs and ClassesOOP, ADTs and Classes Class Definition, Implementation and UseClass Definition, Implementation and Use Constructors and Value SemanticsConstructors and Value Semantics
More on Classes (Lecture 3)More on Classes (Lecture 3) Namespace and DocumentationNamespace and Documentation Classes and ParametersClasses and Parameters Operator OverloadingOperator Overloading
Xiaoyan Li, 2007Xiaoyan Li, 2007 33
Standard Library &NamespaceStandard Library &Namespace
ANSI/ISO C++ Standard ANSI/ISO C++ Standard ( (late 1990s)late 1990s) aids in writing portable code with different compliersaids in writing portable code with different compliers
C++ Standard Library ( 1999 C++ compilers provide full SL)C++ Standard Library ( 1999 C++ compilers provide full SL) Provides a group of declared constants, data types and functions, such Provides a group of declared constants, data types and functions, such
as I/O and mathas I/O and math Use new “include directive” such as Use new “include directive” such as #include <iostream>#include <iostream> without .h without .h
Standard NamespaceStandard Namespace All the items in the new header files are part of a feature called All the items in the new header files are part of a feature called
standard namespace standard namespace stdstd When you use one of the new header files, you should useWhen you use one of the new header files, you should use
using namespace stdusing namespace std which allows you to use all items from the standard namespace.which allows you to use all items from the standard namespace.
Xiaoyan Li, 2007Xiaoyan Li, 2007 44
Namespace and Documentation Namespace and Documentation
Goal: Goal: to make our new point class easily available to any to make our new point class easily available to any
programs any time withoutprograms any time without revealing all the detailsrevealing all the details worrying about name conflictsworrying about name conflicts
Three steps to fulfill the goalThree steps to fulfill the goal Creating a namespaceCreating a namespace Writing the header fileWriting the header file Writing the implementation fileWriting the implementation file
Xiaoyan Li, 2007Xiaoyan Li, 2007 55
NamespaceNamespace
Question:Question: You may use two versions of point classes in the same You may use two versions of point classes in the same
programprogram
Solution is to use the namespace techniqueSolution is to use the namespace technique A namespace is a name that a programmer selects to A namespace is a name that a programmer selects to
identify a portion of his/her workidentify a portion of his/her work The name should be descriptive, better include part of The name should be descriptive, better include part of
your real name and other features for uniquenessyour real name and other features for uniqueness
Namespace li_mtholyoke_csc211_lecture_3{ // any item that belong to the namespace is written here}
Xiaoyan Li, 2007Xiaoyan Li, 2007 66
Namespace groupingsNamespace groupings
All work that is part of our namespace must be in a namespace All work that is part of our namespace must be in a namespace groupinggrouping
A single namespace such as A single namespace such as li_mtholyoke_csc211_lecture_3 may have several namespace groupingsmay have several namespace groupings
They don’t need in the same files, typically in two separate filesThey don’t need in the same files, typically in two separate files Class definition in a Class definition in a header fileheader file Member function definitions in a separate Member function definitions in a separate implementation fileimplementation file
Xiaoyan Li, 2007Xiaoyan Li, 2007 77
Header File for a ClassHeader File for a Class
A separate header file for a new class A separate header file for a new class point.hpoint.h
At the top place the At the top place the documentationdocumentation (how to use) (how to use) Followed by class Followed by class definitiondefinition (but not the (but not the
implementation)implementation) Place class definition inside a Place class definition inside a namespacenamespace Place a “Place a “macro guardmacro guard” around the entire thing” around the entire thing Documentation should include a comment Documentation should include a comment
indicating that the indicating that the value semanticsvalue semantics is safe to use is safe to use
#ifndef MAIN_SAVITCH_POINT_H
#define MAIN_SAVITCH_POINT_H
namespace main_savitch_2A
{
class point
{
};
} #endif
Xiaoyan Li, 2007Xiaoyan Li, 2007 88
Implementation File for a ClassImplementation File for a Class
A separate implementation file for a new class A separate implementation file for a new class point.cxxpoint.cxx (or point.cpp, point.C)(or point.cpp, point.C)
At the top place a small comment indicating the At the top place a small comment indicating the documentationdocumentation is in the header file is in the header file
Followed by Followed by include directiveinclude directive #include “point.h”#include “point.h” reopen the reopen the namespace namespace and place the and place the
implementation implementation of member functions inside the of member functions inside the namespacenamespace
Xiaoyan Li, 2007Xiaoyan Li, 2007 99
Using Items in a NamespaceUsing Items in a Namespace
A separate program file for using calsses A separate program file for using calsses pointmain1.cxxpointmain1.cxx
At the top place an include directive At the top place an include directive #include “point.h”#include “point.h” Three ways to use the items in a Three ways to use the items in a namespacenamespace
using namespace main_savitch_2A;using namespace main_savitch_2A; using main_savitch_2A::point;using main_savitch_2A::point; main_savitch_2A::point p1;main_savitch_2A::point p1;
Question: shall we include the implementation file Question: shall we include the implementation file in pointmain1.cxx?in pointmain1.cxx?
Xiaoyan Li, 2007Xiaoyan Li, 2007 1010
OutlineOutline
A Review of C++ Classes (Lecture 2)A Review of C++ Classes (Lecture 2) OOP, ADTs and ClassesOOP, ADTs and Classes Class Definition, Implementation and UseClass Definition, Implementation and Use Constructors and Value SemanticsConstructors and Value Semantics
More on Classes (Lecture 3)More on Classes (Lecture 3) Namespace and DocumentationNamespace and Documentation Classes and ParametersClasses and Parameters Operator OverloadingOperator Overloading
Xiaoyan Li, 2007Xiaoyan Li, 2007 1111
Classes and ParametersClasses and Parameters
Default parametersDefault parameters when no or only part of the parameters are when no or only part of the parameters are
provided in calling functionprovided in calling function Types of parametersTypes of parameters
value parametersvalue parameters reference parametersreference parameters constant reference parametersconstant reference parameters
Return value is a classReturn value is a class
Xiaoyan Li, 2007Xiaoyan Li, 2007 1212
Default argumentsDefault arguments
A default argument is a value that will be A default argument is a value that will be used for an argument when a programmer used for an argument when a programmer does not provide an actual argument when does not provide an actual argument when calling a functioncalling a function
Default arguments may be listed in the Default arguments may be listed in the prototype of a functionprototype of a function Syntax: Syntax: Type_name var_name = default_valueType_name var_name = default_value
Xiaoyan Li, 2007Xiaoyan Li, 2007 1313
Default arguments – rulesDefault arguments – rules
The default argument is only specified once – in The default argument is only specified once – in the prototype – not in the implementationthe prototype – not in the implementation
No need to specify all the arguments as default No need to specify all the arguments as default but those as default must be rightmost in the but those as default must be rightmost in the parameter listparameter list
In a call, arguments with default may be omitted In a call, arguments with default may be omitted from the right end.from the right end.
Example of a prototype:Example of a prototype:
int date_check (int year, int monthint date_check (int year, int month = 1 = 1, int date, int date =1 =1););
Xiaoyan Li, 2007Xiaoyan Li, 2007 1414
Default arguments – rulesDefault arguments – rules
The default argument is only specified once – in The default argument is only specified once – in the prototype – not in the implementationthe prototype – not in the implementation
No need to specify all the arguments as default but No need to specify all the arguments as default but
those as default must be the rightmost in the those as default must be the rightmost in the parameter listparameter list
In a call, arguments with default may be omitted In a call, arguments with default may be omitted from the right end.from the right end.
Example:Example:
int date_check (int year, int monthint date_check (int year, int month = 1 = 1, int date, int date =1 =1); // okay); // okay
int date_check (int year int date_check (int year =2002=2002, int month, int month = 1 = 1, int date); , int date); // ?// ?
Xiaoyan Li, 2007Xiaoyan Li, 2007 1515
Default arguments – rulesDefault arguments – rules
The default argument is only specified once – in The default argument is only specified once – in the prototype – not in the implementationthe prototype – not in the implementation
No need to specify all the arguments as default No need to specify all the arguments as default but those as default must be rightmost in the but those as default must be rightmost in the parameter listparameter list
In a call, arguments with default may be omitted In a call, arguments with default may be omitted from the right end.from the right end.
Prototype:Prototype:
int date_check (int year, int month = 1, int date =1); int date_check (int year, int month = 1, int date =1);
Usage in the calling functionUsage in the calling function
date_check(2002); // uses default for both month and datedate_check(2002); // uses default for both month and date
date_check(2002, 9); // uses default for date =1date_check(2002, 9); // uses default for date =1
date_check(2002, 9, 5); // does not use defaultsdate_check(2002, 9, 5); // does not use defaults
Xiaoyan Li, 2007Xiaoyan Li, 2007 1616
How can we apply default arguments to a constructor ?How can we apply default arguments to a constructor ?
Xiaoyan Li, 2007Xiaoyan Li, 2007 1717
Default Constructor revisitedDefault Constructor revisited
A default constructor can be provided by using default A default constructor can be provided by using default argumentsarguments
Instead of define two constructors and have two Instead of define two constructors and have two implementationsimplementations
class point {public: point(); point(double init_x, double init_y); …};
Xiaoyan Li, 2007Xiaoyan Li, 2007 1818
Default Constructor revisitedDefault Constructor revisited
A default constructor can be provided by using default A default constructor can be provided by using default argumentsarguments
We can define just one constructors with default We can define just one constructors with default arguments for all of its argumentsarguments for all of its arguments
class point {public: point(double init_x=0.0, double init_y =0.0); …};
Xiaoyan Li, 2007Xiaoyan Li, 2007 1919
Default Constructor revisitedDefault Constructor revisited
In using the class, we can have three declarationsIn using the class, we can have three declarations
The implementation of the constructor with default The implementation of the constructor with default argument is the same as the usual one...argument is the same as the usual one...
point a(-1, 0.8); // uses the usual constructor with // two argumentspoint b(-1); // uses –1 for the first, // but use default for the second
point c; // uses default arguments for both; // default constructor: // no argument, no parentheses!
Xiaoyan Li, 2007Xiaoyan Li, 2007 2020
Constructors: ImplementationConstructors: Implementation
point::point(double init_x, double init_y){ x = init_x; y = init_y;}
And for the most part, the constructor is no different And for the most part, the constructor is no different than any other member functions.than any other member functions.
But recall that there are 3 special features about But recall that there are 3 special features about constructor...and 4 for this with default arguments!constructor...and 4 for this with default arguments!
xx
-2 -1 0 1 2-2 -1 0 1 2
2 2 1 1 0 0 -1-1-2-2
yy
pp
Xiaoyan Li, 2007Xiaoyan Li, 2007 2121
Second topic about parameters...Second topic about parameters...
Classes as parametersClasses as parameters
Xiaoyan Li, 2007Xiaoyan Li, 2007 2222
Class as type of parameterClass as type of parameter
A class can be used as the type of a A class can be used as the type of a function’s parameter, just like any other function’s parameter, just like any other data typedata type Value parametersValue parameters Reference parametersReference parameters Const reference parametersConst reference parameters In fact you can also have In fact you can also have const value const value
parameters, parameters, even if this does not make many even if this does not make many sensessenses
Xiaoyan Li, 2007Xiaoyan Li, 2007 2323
Value parametersValue parameters
How many shifts to move p into the first quadHow many shifts to move p into the first quad
Function implementation:
int shifts_needed(point p){ int answer = 0; while ((p.get_x() <0) || (p.get_y()<0)) { p.shift(1,1); answer++; } return answer;}
In calling program:
point a(-1.5,-2.5);cout << a.get_x() << a.get_y() << endl;cout << shifts_needed(a) << endl;cout << a.get_x() << a.get_y() << endl;
xx
-2 -1 0 1 2-2 -1 0 1 2
2 2 1 1 0 0 -1-1-2-2
yy
pp
formal parameterformal parameter
actu
al a
rgu
men
tac
tual
arg
um
ent -1.5, -2.5
3
1.5, 0.5 ?
-1.5, -2.5
3
-1.5, -2.5
Xiaoyan Li, 2007Xiaoyan Li, 2007 2424
Value parametersValue parameters
A value parameter is declared by writing A value parameter is declared by writing type-nametype-name parameter-nameparameter-name
Any change made to the Any change made to the formal parameterformal parameter within the body of the function does within the body of the function does notnot change change the the actual argumentactual argument from the calling program from the calling program
The formal parameter is implemented as a local The formal parameter is implemented as a local variable of the function, and the class’s variable of the function, and the class’s copy copy constructorconstructor is used to initialize the formal is used to initialize the formal parameter as a copy of the actual argument parameter as a copy of the actual argument
Xiaoyan Li, 2007Xiaoyan Li, 2007 2525
Reference parametersReference parameters
Actually move p into the first quadrantActually move p into the first quadrant
Function implementation (almost the same except &):
int shift_to_1st_quad(point& p){ int shifts; while ((p.get_x() <0) || (p.get_y()<0)) { p.shift(1,1); shifts++; } return shifts;}
In calling program:
point a(-1.5,-2.5);cout << a.get_x() << a.get_y() << endl;cout << shift_to_1st_quad(a) << endl;cout << a.get_x() << a.get_y() << endl;
xx
-2 -1 0 1 2-2 -1 0 1 2
2 2 1 1 0 0 -1-1-2-2
yy
pp
type_name & para_name
type_name & para_name
NO
& !
NO
& !
-1.5, -2.5
3
1.5, 0.5
Xiaoyan Li, 2007Xiaoyan Li, 2007 2626
Reference parametersReference parameters
A reference parameter is declared by writing A reference parameter is declared by writing type-name&type-name& parameter-nameparameter-name
Any use of the Any use of the formal parameterformal parameter within the body within the body of the function will of the function will accessaccess the the actual argumentactual argument from the calling program; change made to the from the calling program; change made to the parameter in the body of the function will alter the parameter in the body of the function will alter the argumentargument
The formal parameter is merely another name of The formal parameter is merely another name of the argument used in the body of the function! the argument used in the body of the function!
Xiaoyan Li, 2007Xiaoyan Li, 2007 2727
const reference parametersconst reference parameters
A const reference parameter is declared by writing A const reference parameter is declared by writing const type-name&const type-name& parameter-nameparameter-name
A solution that provides the efficiency of a A solution that provides the efficiency of a reference parameter along with the security of a reference parameter along with the security of a value parameter.value parameter.
ExampleExample ( ( newpoint.cxxnewpoint.cxx)) double distance (const point& p1, const point& p2)double distance (const point& p1, const point& p2)
point p1 and p2 cannot be changed (point p1 and p2 cannot be changed (TEST!TEST!))
Xiaoyan Li, 2007Xiaoyan Li, 2007 2828
Third topic about parameters and functions of a class...Third topic about parameters and functions of a class...
Class as return valueClass as return value
Xiaoyan Li, 2007Xiaoyan Li, 2007 2929
Class as return valueClass as return value
point middle(const point& p1, const point& p2) { double x_midpoint, y_midpoint;
// Compute the x and y midpoints x_midpoint = (p1.get_x( ) + p2.get_x( )) / 2; y_midpoint = (p1.get_y( ) + p2.get_y( )) / 2;
// Construct a new point and return it point midpoint(x_midpoint, y_midpoint); return midpoint;
}
Xiaoyan Li, 2007Xiaoyan Li, 2007 3030
Class as return valueClass as return value
The type of a function’s return value may be a lassThe type of a function’s return value may be a lass Often the return value will be stored in a Often the return value will be stored in a local local
variablevariable of the function (such as of the function (such as midpointmidpoint), but ), but not always (could be in a formal parameter)not always (could be in a formal parameter)
C++ return statement uses the C++ return statement uses the copy constructorcopy constructor to copy the function’s return value to a temporary to copy the function’s return value to a temporary location before returning the value to the calling location before returning the value to the calling programprogram
Example ( Ch 2.4, Look into Example ( Ch 2.4, Look into newpoint.cxxnewpoint.cxx)) point middle(const point& p1, const point& p2)point middle(const point& p1, const point& p2)
Xiaoyan Li, 2007Xiaoyan Li, 2007 3131
OutlineOutline
A Review of C++ Classes (Lecture 2)A Review of C++ Classes (Lecture 2) OOP, ADTs and ClassesOOP, ADTs and Classes Class Definition, Implementation and UseClass Definition, Implementation and Use Constructors and Value SemanticsConstructors and Value Semantics
More on Classes (Lecture 3)More on Classes (Lecture 3) Namespace and DocumentationNamespace and Documentation Classes and ParametersClasses and Parameters Operator OverloadingOperator Overloading
Xiaoyan Li, 2007Xiaoyan Li, 2007 3232
Operator OverloadingOperator Overloading
Binary functions and binary operatorsBinary functions and binary operators Overloading arithmetic operationsOverloading arithmetic operations Overloading binary comparison operationsOverloading binary comparison operations Overloading input/output functionsOverloading input/output functions Friend functions – when to useFriend functions – when to use
Xiaoyan Li, 2007Xiaoyan Li, 2007 3333
Operator OverloadingOperator Overloading
Question:Question: Can we perform arithmetic operations (+ - * /) Can we perform arithmetic operations (+ - * /)
or comparison operations (>, ==, <, etc.) or or comparison operations (>, ==, <, etc.) or assignment operation (=) with a new class?assignment operation (=) with a new class?
point speed1(5,7)point speed2(1,2);point difference;
if (speed1 != speed2 )difference = speed1 - speed2;
Xiaoyan Li, 2007Xiaoyan Li, 2007 3434
Operator OverloadingOperator Overloading
Question:Question: Can we perform arithmetic operations (+ - * /) Can we perform arithmetic operations (+ - * /)
or comparison operations (>, ==, <, etc.) or or comparison operations (>, ==, <, etc.) or assignment operation (=) with a new class?assignment operation (=) with a new class?
point speed1(5,7)point speed2(1,2);point difference;
if (speed1 != speed2 )difference = speed1 - speed2;
Automatic
assignment opera
tor
Automatic
assignment opera
tor
Xiaoyan Li, 2007Xiaoyan Li, 2007 3535
Operator OverloadingOperator Overloading
Answer is NOAnswer is NO unless you define a unless you define a binary functionbinary function that tells that tells
exactly what “!=” or “+” meansexactly what “!=” or “+” means
point speed1(5,7)point speed2(1,2);point difference;
if (speed1 != speed2 )difference = speed1 - speed2;
Xiaoyan Li, 2007Xiaoyan Li, 2007 3636
Operator OverloadingOperator Overloading
Binary FunctionBinary Function A function with two A function with two
argumentsarguments
Binary OperatorBinary Operator A operator with two A operator with two
operandsoperands
p = p1 + p2; p = p1 + p2; p = add( p1, p2); p = add( p1, p2);
Operator Overloading is to define the meaning of an existing operator for a new class
Instead of defining
point add(point p1, point p2)
We define
point operator+(point p1, point p2)
Xiaoyan Li, 2007Xiaoyan Li, 2007 3737
Overloading arithmetic operatorsOverloading arithmetic operators
+, -, *, / , %+, -, *, / , %point operator+(const point& p1, const point& p2)
//Postcondition: the sum of p1 and p2 is returned.
{
double x_sum, y_sum;
x_sum = (p1.get_x() + p2.get_x());
y_sum = (p1.get_y() + p2.get_y());
point sum(x_sum, y_sum);
return sum;
}
Xiaoyan Li, 2007Xiaoyan Li, 2007 3838
Overloading arithmetic operatorsOverloading arithmetic operators
Apart from the peculiar name Apart from the peculiar name operator+operator+, the function is , the function is just like any other functionjust like any other function
The overloaded operator + is used in a program just like The overloaded operator + is used in a program just like any other use of +any other use of + p = p1+ p2p = p1+ p2;;
When you overload an operator +, the usual usage of + When you overload an operator +, the usual usage of + is still available is still available
Note the uses of Note the uses of const reference parameters since…const reference parameters since… member functions get_x and get_y instead of variablesmember functions get_x and get_y instead of variables the function is a nonmember function the function is a nonmember function
Xiaoyan Li, 2007Xiaoyan Li, 2007 3939
Overloading arithmetic operatorsOverloading arithmetic operators
Method 1: Nonmember function p = p1+p2Method 1: Nonmember function p = p1+p2point operator+(const point& p1, const point& p2)
//Postcondition: the sum of p1 and p2 is returned.
{
double x_sum, y_sum;
x_sum = (p1.get_x() + p2.get_x());
y_sum = (p1.get_y() + p2.get_y());
point sum(x_sum, y_sum);
return sum;
}
Xiaoyan Li, 2007Xiaoyan Li, 2007 4040
Overloading arithmetic operatorsOverloading arithmetic operators
Method 2: Member function p = p1+p2Method 2: Member function p = p1+p2point point::operator+(const point& p2) const//Postcondition: the sum of activating object (p1) and argument p2 is returned.{
double x_sum, y_sum;
x_sum = (x + p2.get_x());
y_sum = (y + p2.get_y());
point sum(x_sum, y_sum);
return sum;
}
Xiaoyan Li, 2007Xiaoyan Li, 2007 4141
Overloading arithmetic operatorsOverloading arithmetic operators
Overloading using nonmember functionOverloading using nonmember function PROs: two arguments on equal footingPROs: two arguments on equal footing CONs: cannot use the member variablesCONs: cannot use the member variables
Alternative ways to overload a binary functionAlternative ways to overload a binary function Member functionMember function
PROs: can use member variablesPROs: can use member variables CONs: p1 activate the operator with argument p2CONs: p1 activate the operator with argument p2
Which way do you prefer?Which way do you prefer?
Xiaoyan Li, 2007Xiaoyan Li, 2007 4242
Overloading comparison operatorsOverloading comparison operators
====, != , <, >, <=, >=, != , <, >, <=, >=bool operator==(const point& p1, const point& p2)
//Postcondition: the return is true if p1 and p2 are identical; otherwise return is false.
{
return
(p1.get_x() == p2.get_x())
&&
(p1.get_y() == p2.get_y());
}
Xiaoyan Li, 2007Xiaoyan Li, 2007 4343
Overloading comparison operatorsOverloading comparison operators
==, ==, !=!= , <, >, <=, >= , <, >, <=, >=bool operator!=(const point& p1, const point& p2)
//Postcondition: the return is true if p1 and p2 are NOT identical; otherwise return is false.
{
return
(p1.get_x() != p2.get_x())
||
(p1.get_y() != p2.get_y());
}
Xiaoyan Li, 2007Xiaoyan Li, 2007 4444
Overloading comparison operatorsOverloading comparison operators
==, ==, !=!= , <, >, <=, >= , <, >, <=, >=
Or use the overloaded operator for easy Or use the overloaded operator for easy implementationimplementation
bool operator!=(const point& p1, const point& p2)
//Postcondition: the return is true if p1 and p2 are NOT identical; otherwise return is false.
{
return !(p1== p2);
}
Xiaoyan Li, 2007Xiaoyan Li, 2007 4545
Overloading I/O operatorsOverloading I/O operators
Input (>>) & Output (<<) for a new class: Input (>>) & Output (<<) for a new class: <<<<
Q1: how to use this overloaded operator?Q1: how to use this overloaded operator?
ostream& operator<<(ostream& outs, const point& source)// Postcondition: The x and y coordinates of source have been // written to outs. The return value is the ostream outs.// Library facilities used: iostream {
outs << source.get_x( ) << " " << source.get_y( );return outs;
}
cout << p ; cout << p ;
Xiaoyan Li, 2007Xiaoyan Li, 2007 4646
Overloading I/O operatorsOverloading I/O operators
Input (>>) & Output (<<) for a new class: Input (>>) & Output (<<) for a new class: <<<<
Q2: why is outs a reference parameter but NOT const?Q2: why is outs a reference parameter but NOT const?
ostream& operator<<(ostream& outs, const point& source)// Postcondition: The x and y coordinates of source have been // written to outs. The return value is the ostream outs.// Library facilities used: iostream {
outs << source.get_x( ) << " " << source.get_y( );return outs;
}
Need change actual argument coutNeed change actual argument cout
Xiaoyan Li, 2007Xiaoyan Li, 2007 4747
Overloading I/O operatorsOverloading I/O operators
Input (>>) & Output (<<) for a new class: Input (>>) & Output (<<) for a new class: <<<<
Q3: why return ostream&?Q3: why return ostream&?
ostream& operator<<(ostream& outs, const point& source)// Postcondition: The x and y coordinates of source have been // written to outs. The return value is the ostream outs.// Library facilities used: iostream {
outs << source.get_x( ) << " " << source.get_y( );return outs;
}
For chaining: cout << “The point is” << p << endl;For chaining: cout << “The point is” << p << endl;
Xiaoyan Li, 2007Xiaoyan Li, 2007 4848
Overloading I/O operatorsOverloading I/O operators
Input (>>) & Output (<<) for a new class: Input (>>) & Output (<<) for a new class: <<<<
Q4: How to overload the input operator Q4: How to overload the input operator >>>> ? ?
ostream& operator<<(ostream& outs, const point& source)// Postcondition: The x and y coordinates of source have been // written to outs. The return value is the ostream outs.// Library facilities used: iostream {
outs << source.get_x( ) << " " << source.get_y( );return outs;
}
Xiaoyan Li, 2007Xiaoyan Li, 2007 4949
Overloading I/O operatorsOverloading I/O operators
Input (>>) & Output (<<) for a new class: Input (>>) & Output (<<) for a new class: >>>>
NO const for both istream and pointNO const for both istream and point Problem: send input directly to private members!Problem: send input directly to private members!
istream& operator>>(istream& ins, point& target)// Postcondition: The x and y coordinates of target have been // read from ins. The return value is the istream ins.// Library facilities used: iostream {
ins >> target. x >> target.y;return ins;
}
Xiaoyan Li, 2007Xiaoyan Li, 2007 5050
Three possible solutions Three possible solutions
Use a member function for overloading the Use a member function for overloading the input function input function (try!)(try!)
Write new member functions to set a Write new member functions to set a point’s coordinates point’s coordinates separatelyseparately so they can so they can be used within the input function be used within the input function (try!)(try!)
Grant special permission for the input Grant special permission for the input function to access the private variablesfunction to access the private variables using a friend functionusing a friend function
Xiaoyan Li, 2007Xiaoyan Li, 2007 5151
Friend FunctionFriend Function
A friend function is NOT a member A friend function is NOT a member function, but it still has access to the private function, but it still has access to the private members of its parametersmembers of its parameters
class point {public: … … // FRIEND FUNCTION friend istream& operator>>(istream& ins, point& target);private: …};
Xiaoyan Li, 2007Xiaoyan Li, 2007 5252
Overloading I/O operatorsOverloading I/O operators
Input (>>) & Output (<<) for a new class: Input (>>) & Output (<<) for a new class: >>>>
Problem Problem is resolved by using friend function, no is resolved by using friend function, no change in implementationchange in implementation
istream& operator>>(istream& ins, point& target)// Postcondition: The x and y coordinates of target have been // read from ins. The return value is the istream ins.// Library facilities used: iostream {
ins >> target. x >> target.y;return ins;
}
Xiaoyan Li, 2007Xiaoyan Li, 2007 5353
Overloading I/O operatorsOverloading I/O operators
Input (>>) & Output (<<) for a new class: Input (>>) & Output (<<) for a new class: >>>>
However it is always a good practice to put a comment However it is always a good practice to put a comment lineline
istream& operator>>(istream& ins, point& target)// Postcondition: The x and y coordinates of target have been // read from ins. The return value is the istream ins.// Library facilities used: iostream// Friend of point class {
ins >> target. x >> target.y;return ins;
}
Xiaoyan Li, 2007Xiaoyan Li, 2007 5454
Summary of ClassesSummary of Classes
A Review of C++ Classes (Lecture 2)A Review of C++ Classes (Lecture 2) OOP, ADTs and ClassesOOP, ADTs and Classes Class Definition, Implementation and UseClass Definition, Implementation and Use Constructors and Value SemanticsConstructors and Value Semantics
More on Classes (Lecture 3)More on Classes (Lecture 3) Namespace and DocumentationNamespace and Documentation Classes and ParametersClasses and Parameters Operator OverloadingOperator Overloading
Xiaoyan Li, 2007Xiaoyan Li, 2007 5555
point class: Putting things togetherpoint class: Putting things together
Header file (Header file (newpoint.hnewpoint.h)) Documentation including pre- & post-conditionsDocumentation including pre- & post-conditions Class definitions for any new classes //inlineClass definitions for any new classes //inline Prototype of nonmember functions (e,g. for overloading)Prototype of nonmember functions (e,g. for overloading) Place the Class and Prototype inside a namespacePlace the Class and Prototype inside a namespace
Implementation file (Implementation file (newpoint.cxxnewpoint.cxx)) An include directive to include the header fileAn include directive to include the header file Implementation of each function (except inline)Implementation of each function (except inline) Implementation of each friend and other nonmemberImplementation of each friend and other nonmember Use the same namespace for implementationUse the same namespace for implementation
Calling program file (Calling program file (pointmain2.cxxpointmain2.cxx)) Three ways to use the items in a namespaceThree ways to use the items in a namespace
Xiaoyan Li, 2007Xiaoyan Li, 2007 5656
Exercises and AssignmentsExercises and Assignments
Writing HomeworkWriting Homework Alternative implementation of operator >>Alternative implementation of operator >>
Self-Test Exercises (do not turn in)Self-Test Exercises (do not turn in) 1, 4 ,513,15,17,21,23, 25,28,311, 4 ,513,15,17,21,23, 25,28,31
Reading before the next lectureReading before the next lecture Chapter 3. Container ClassesChapter 3. Container Classes
Programming Assignment 1Programming Assignment 1 Detailed guidelines online!Detailed guidelines online!
check schedule on our course web page check schedule on our course web page