Document 15057522

advertisement
Course Name: High Level Programming Language
Year
: 2010
Operator Overloading
Lecture 8
Learning Outcomes
At the end of this lecture, students are
capable of:
• File handling
• Operator overloading
• Exceptions
3
File Handling *
• Streams in C++
– Input Stream
– Output Stream
– iostream: combination of input and output stream
• Implementation of Stream
– cin
– cout
• Fstream is a superset of iostream
– Ifstream
– Ofstream
– Fstream – using multiple inheritance (discuss next week)
* ref.: http://ocw.mit.edu/NR/rdonlyres/Electrical-Engineering-and-Computer-Science/6-096January--IAP--2009/B5E0C56C-A391-40F3B77D-1CBB17644B89/0/lec9.pdf
Bina Nusantara University
4
File Handling Samples
• cout << “halo”; // << is insertion operator
• string s;
cin >> s; // >> is extraction operator
• fstream f; // declare an object of class fstream
f.open(“abc.txt”, ios::out) //open file using a stream
f << “Halo” << endl; //write to file using the object declared
f << “Dunia” << endl; f.close(); // close the file
• f.open(“abc.txt”,ios::in) //opening the file using input stream
string s; f >> s; // read from file using the object declared
f.close(); // close the file
• Note: ios::out, ios::in are called mode of operation, the other two are
ios::trunc(ate) and ios:app(end)
Bina Nusantara University
5
Review -- Function Signatures
• A function signature is what the
compiler and linker use to identify a
function.
• In C, functions are identified only by
their name.
• In C++, a function’s signature includes
its name, parameters, and (for member
functions) const. It does NOT include
the return type.
Bina Nusantara University
6
Function Overloading
• We still need separate functions, but they can all have
the same name.
– void swap (int& a, int& b);
– void swap (double& a, double& b);
– void swap (struct bob& a, struct bob& b);
Bina Nusantara University
7
What is operator overloading?
• Changing the definition of an operator, so it can be
applied on the objects of a class, is called operator
overloading.
• To overload an operator, we need to write a function
for the operator we are overloading.
Special cases
• The assignment operator (=) may be used with
every class without explicit overloading.
• The default behavior of the assignment operator
is a memberwise assignment of the data
members of the class.
• The address operator (&) may also be used with
objects of any class without explicit overloading.
• It returns the address of the object in memory.
Explicit overloading of the
assignment operator
• The default overloading is not enough for
classes with pointer members.
void operator=(class_name&);
class string {
private:
char *s;
int size;
public:
string(char *);
// constructor
~string();
// destructor
void operator=(string&);
void print();
void copy(char *);
};
void string::operator=(string& old_str)
{
char *tmp;
size = old_str.size;
tmp = new char[size+1]; // assign new memory
strcpy(tmp, old_str.s);
delete [] s;
// must release previously assigned memory
s = tmp;
}
void main()
{
string str1("George");
string str2("Mary");
string str3("John");
str2 = str1;
str3.copy("Ha ha");
str1.print(); // what is printed ?
str2.print();
}
str1.print(); // what is printed now ?
str2.print();
Differences between copy
constructor and assignment
operator
• The copy constructor creates a new object.
• The assignment operator works on an already valid
object.
Another example:
overloading the [] operator
class Array {
private:
int numElems;
int *arr;
public:
Array(int); // constructor
~Array(); // destructor
int& operator[](int);
};
Array::Array(int n)
{
numElems = n;
arr = new int[n];
}
Array::~Array()
{
delete [] arr;
}
int& Array::operator[](int index)
{
if ((index < 0) || (index >= numElems)) {
cout << "Out of bounds error !!" << endl;
exit(0); // error: invalid index !!
}
else
return(arr[index]);
}
void main()
{
int i;
Array A(10);
for(i=0; i<=10; i++) // i=10: error !!
A[i] = i;
}
Comments on operator overloading
• Attempting to create new operators via
operator overloading is a syntax error.
• Attempting to change the "arity" of an
operator via operator overloading is a syntax
error.
• Overloading is allowed only if at least one
operand is a class instance (e.g., you cannot
overload an operator to take two integers as
operands).
Exception Handling *
• In C++, Exception Handling allows the programmer to
notify the user when there is a problem.
• The problem can be handled in the notifying routine, or
passed along to the caller.
• Please note, this terminology is included only for basic
information about “exception handling”, please refer to
the address below for more detail explanation:
* Ref.:
http://www.google.nl/url?sa=t&source=web&ct=res&cd=9&ved=0CCoQFjAI&url=http%3A%2F%2Fwww.ingberconsulting.com%2FCS162
Livermore%2FCourseMaterials%2FExceptionHandling.ppt&rct=j&q=exception+exercise+%40filetype%3Appt&ei=lmRUS6r4F4fUsgO_uK
D1Bw&usg=AFQjCNG6D2maFx5bW4h26DRwMPHpL4xU6A
Bina Nusantara University
16
Conclusions
• File handling in c++ is handled by <fstream>
• Operator overloading is a way to read coding easier.
• Exception handling is a way like assert function (in c
language), but implemented in a class.
17
Topic For Next Week
• Inheritance
• Assignment:
– Read chapter 8 – Derived Classes, and do the following exercise, taken from chapter 8 page
168:
Consider a Year class which divides the days in a year into work days and off days. Because each
day has a binary value, Year is easily derived from BitVec (for definition of class BitVec, please take a look at
page 144 of chapter 8 of CppEssentials.pdf):
18
Assignment cont.
enum Month {
Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
};
Class Year : public BitVec {
Public:
Year
(const short year);
Void Workday (const short day); // set day as work day
Void OffDay (const short day); // set day as off day
Bool working (const short day); // true if a work day
Short Day (const short day,
// convert date to day
const Month month, const short year);
Protected:
short year;
// calendar year
};
Days are sequentially numbered from the beginning of the year, starting at 1 for
January 1st. Complete the Year class by implementing its member functions.
Bina Nusantara University
19
Download