Download - c++ notes by vikas sharma
-
8/14/2019 c++ notes by vikas sharma
1/18
1Dale Roberts
Operator OverloadingOperator Overloading
Friend Functions & Special FormsFriend Functions & Special Forms
Dale Roberts, Lecturer
Computer Science, IUPUI
E-mail: [email protected]
Department of Computer and Information Science,
School of Science, IUPUI
-
8/14/2019 c++ notes by vikas sharma
2/18
Dale Roberts 2
Operator Overloading Using a Friend FunctionOperator Overloading Using a Friend Function
Number of Parameters Accepted by an Overloaded Friend OperatorNumber of Parameters Accepted by an Overloaded Friend OperatorFunction Depend Upon the Operator Type -- One for Unary Operators andFunction Depend Upon the Operator Type -- One for Unary Operators and
Two for Binary OperatorsTwo for Binary Operators
class complex{class complex{int re, im;int re, im;
public:public:complex(int ip1 = 0, int ip2 = 0)complex(int ip1 = 0, int ip2 = 0)
:re(ip1), im(ip2){}:re(ip1), im(ip2){}friend complex operator+(complex, complex);friend complex operator+(complex, complex);};};//Friend Operator + Function//Friend Operator + Functioncomplex operator+(complex a, complex b)complex operator+(complex a, complex b)
{return complex(a.re+b.re, a.im+b.im);}{return complex(a.re+b.re, a.im+b.im);}
main(){main(){complex one(1,1), two(2,2), three;complex one(1,1), two(2,2), three;three = one + two; //three = operator+(one, two)three = one + two; //three = operator+(one, two)
}} Is a friend function necessary in this case?
No because LH operand is an instance of the class.
-
8/14/2019 c++ notes by vikas sharma
3/18
Dale Roberts 3
Operator Functions as Class Members vs. asOperator Functions as Class Members vs. as friendfriend FunctionsFunctions
Non-member overloaded operator functionsNon-member overloaded operator functions
Enable the operator to be commutativeEnable the operator to be commutative
HugeInteger bigInteger;HugeInteger bigInteger;
int integer;int integer;bigInteger = integer + bigInteger;bigInteger = integer + bigInteger;
oror
bigInteger = bigInteger + integer;bigInteger = bigInteger + integer;
-
8/14/2019 c++ notes by vikas sharma
4/18
Dale Roberts 4
Global Operator OverloadingGlobal Operator OverloadingSimilar toSimilar to friendfriendFunction Overloading, Except the KeywordFunction Overloading, Except the Keyword friendfriend is Omitted andis Omitted andGlobal Functions CANNOT ACCESSGlobal Functions CANNOT ACCESS privateprivate MembersMembers
class complex{ //All Public Members!class complex{ //All Public Members!public:public:int re, im;int re, im;complex(int ip1 = 0, int ip2 = 0)complex(int ip1 = 0, int ip2 = 0)
:re(ip1), im(ip2){}:re(ip1), im(ip2){}};};
void operator!(complex a)void operator!(complex a){{
int temp = a.re; a.re = a.im; a.im = temp;int temp = a.re; a.re = a.im; a.im = temp;cout
-
8/14/2019 c++ notes by vikas sharma
5/18
Dale Roberts 5
Overloading of Operators Having a Variable ArityOverloading of Operators Having a Variable Arity
Operators Such asOperators Such as --Can be Unary or BinaryCan be Unary or Binary
Overloading of Such Operators Involves Creating a Unary Function (OneOverloading of Such Operators Involves Creating a Unary Function (One
Operand) and a Binary Function (Two Operands)Operand) and a Binary Function (Two Operands)Only if Both the Forms are Used, They Need to be ImplementedOnly if Both the Forms are Used, They Need to be Implemented
class number{class number{int n;int n;
public:public:
number(int x = 0):n(x){}number(int x = 0):n(x){}number operator-(){n = -n; return *this;}number operator-(){n = -n; return *this;}number operator-(number ip)number operator-(number ip){n = n ip.n; return *this;}{n = n ip.n; return *this;}
};};main(){main(){
number one(1), two(2), three;number one(1), two(2), three;one = -one; //unary operatorone = -one; //unary operatorthree = one - two; //three.n = -3three = one - two; //three.n = -3
}}
-
8/14/2019 c++ notes by vikas sharma
6/18
Dale Roberts 6
Operators with Prefix and Postfix FormsOperators with Prefix and Postfix Forms
Separate Functions for Each -- Prefix andSeparate Functions for Each -- Prefix and
Postfix -- Forms are NeededPostfix -- Forms are NeededPrefix Form is Treated as an Unary OperatorPrefix Form is Treated as an Unary Operator
Postfix Form is Treated as a Binary OperatorPostfix Form is Treated as a Binary Operator
-
8/14/2019 c++ notes by vikas sharma
7/18 Dale Roberts 7
Prefix Overloaded Function -- ExamplePrefix Overloaded Function -- Example
class number{class number{
int n;int n;public:public:
number(int x):n(x){}; //Constructornumber(int x):n(x){}; //Constructor
//prefix operator -- unary//prefix operator -- unary
number operator++();number operator++();};};
number number::operator++(){number number::operator++(){
n++; return *this;}n++; return *this;}
main(){main(){number one(10); //one.n = 10number one(10); //one.n = 10
++one; //one.n = 11++one; //one.n = 11
}}
-
8/14/2019 c++ notes by vikas sharma
8/18 Dale Roberts 8
Postfix Overloaded Function -- ExamplePostfix Overloaded Function -- Example
Postfix Operator is Implemented as a Binary Operator with anPostfix Operator is Implemented as a Binary Operator with an intintArgument with a Default Value of 0 . When specifying anArgument with a Default Value of 0 . When specifying an
overloaded operator for the postfix form of the increment oroverloaded operator for the postfix form of the increment ordecrement operator, the additional argument must be of type int;decrement operator, the additional argument must be of type int;specifying any other type generates an error.specifying any other type generates an error.
class number{class number{
int n;int n;
public:public:number(int x):n(x){}; //Constructornumber(int x):n(x){}; //Constructor
//postfix operator -- binary -- int argument//postfix operator -- binary -- int argument
number operator++(int);number operator++(int);
};};
number number::operator++(int y)number number::operator++(int y)
{if (y != 0) n += y; else n++; return *this;}{if (y != 0) n += y; else n++; return *this;}
-
8/14/2019 c++ notes by vikas sharma
9/18 Dale Roberts 9
Postfix overloaded functionExample (Cont)Postfix overloaded functionExample (Cont)
main()main()
{{number one(10); // one.n = 10number one(10); // one.n = 10
one++; // one.n = 11one++; // one.n = 11
one.operator++(2); // one.n = 13one.operator++(2); // one.n = 13
}}
There is no syntax for using the increment or decrementThere is no syntax for using the increment or decrement
operators to pass these values other than explicit invocation, asoperators to pass these values other than explicit invocation, as
shown in the preceding code. A more straightforward way toshown in the preceding code. A more straightforward way to
implement this functionality is to overload theimplement this functionality is to overload the
addition/assignment operator (+=).addition/assignment operator (+=).
-
8/14/2019 c++ notes by vikas sharma
10/18 Dale Roberts 10
Special Overloading FormsSpecial Overloading Forms
A Few Operators Require Special Treatments DuringA Few Operators Require Special Treatments During
OverloadingOverloadingConversion OperatorConversion Operator
constconstArray OperatorArray Operator
Function Call -- Parenthesis OperatorFunction Call -- Parenthesis Operator
Stream Insertion --Stream Insertion -- > OperatorOperator
Pointer to Member --Pointer to Member -- ->-> OperatorOperator
Assignment OperatorAssignment Operator
newnewOperatorOperator
deletedelete OperatorOperator
-
8/14/2019 c++ notes by vikas sharma
11/18 Dale Roberts 11
Overloading Stream-Insertion and Stream-Extraction OperatorsOverloading Stream-Insertion and Stream-Extraction Operators
OverloadedOverloaded > operatorsoperators
Must have left operand of typesMust have left operand of types ostreamostream&&,, istreamistream&&respectivelyrespectively
It must be a non-member function (left operand not anIt must be a non-member function (left operand not an
object of the class)object of the class)
It must be aIt must be a friendfriendfunction if it accesses private datafunction if it accesses private datamembersmembers
-
8/14/2019 c++ notes by vikas sharma
12/18 Dale Roberts 12
1 // Fig. 18.3: fig18_03.cpp
2 // Overloading the stream-insertion and
3 // stream-extraction operators.
4 #include
5
6 using std::cout;
7 using std::cin;8 using std::endl;
9 using std::ostream;
10 using std::istream;
11
12 #include
13
14 using std::setw;
15
16 class PhoneNumber {
17 friendostream &operator( istream&, PhoneNumber & );
19
20private:
21 char areaCode[ 4 ]; // 3-digit area code and null
22 char exchange[ 4 ]; // 3-digit exchange and null
23 char line[ 5 ]; // 4-digit line and null
24 };
25
26 // Overloaded stream-insertion operator (cannot be
27 // a member function if we would like to invoke it with
28 // cout
-
8/14/2019 c++ notes by vikas sharma
13/18 Dale Roberts 13
31 output > num.exchange; // input exchange
42 input.ignore(); // skip dash (-)
43 input >> setw( 5 ) >> num.line; // input line
44 return input; // enables cin >> a >> b >> c;
45 }46
47 int main()
48 {
49 PhoneNumber phone; // create object phone
50
51 cout > phone invokes operator>> function by
54 // issuing the call operator>>( cin, phone ).
55 cin >> phone;
56
57 // cout
-
8/14/2019 c++ notes by vikas sharma
14/18 Dale Roberts 14
Enter phone number in the form (123) 456-7890:
(800) 555-1212The phone number entered was: (800) 555-1212
-
8/14/2019 c++ notes by vikas sharma
15/18 Dale Roberts 15
Converting between TypesConverting between Types
Cast operatorCast operator
Convert objects into built-in types or other objectsConvert objects into built-in types or other objectsConversion operator must be a non-Conversion operator must be a non-staticstatic member function.member function.
Cannot be aCannot be a friendfriendfunctionfunction
Do not specify return typeDo not specify return typeFor user-defined classFor user-defined classAA
A::operator char *() const; // A to char A::operator char *() const; // A to char A::operator int() const; //A to int A::operator int() const; //A to int
A::operator otherClass() const; //A to otherClassA::operator otherClass() const; //A to otherClass
When compiler seesWhen compiler sees (char *) s(char *) s it callsit calls
s.operator char*()s.operator char*()
-
8/14/2019 c++ notes by vikas sharma
16/18 Dale Roberts 16
Converting between Types (cont)Converting between Types (cont)
The compiler can call these functions to createThe compiler can call these functions to create
temporary objects.temporary objects.IfIfss is not of typeis not of type char *char *
CallsCallsA::operator char *() const;A::operator char *() const; forforcout
-
8/14/2019 c++ notes by vikas sharma
17/18 Dale Roberts 17
Special overloading forms - ExampleSpecial overloading forms - Example
Special Forms ExampleSpecial Forms Example
http://t08specialoverridingformsexample.html/http://t08specialoverridingformsexample.html/http://t08specialoverridingformsexample.html/ -
8/14/2019 c++ notes by vikas sharma
18/18
Dale Roberts 18
AcknowledgementsAcknowledgements
These slides were originally development by Dr. Uday Murthy and Dr. Rajeev
Raje.
Some contents comes from the Deitel slides that accompany your text.
Some information regarding the postfix form the increment and decrement
operators comes from MSDN.