SlideShare a Scribd company logo
Operator Overloading
Overloading Unary Operators
// countpp1.cpp
// increment counter variable with ++ operator
#include <iostream>
using namespace std;
/////////////////////////////////////////////////////////////
///
class Counter
{
private:
unsigned int count; //count
public:
Counter() : count(0) //constructor
{ }
unsigned int get_count() //return count
{ return count; }
void operator ++ () //increment (prefix)
{
++count;
}
};
Keyword
Overloading Unary Operators
int main()
{
Counter c1, c2; //define and initialize
cout << “nc1=” << c1.get_count(); //display
cout << “nc2=” << c2.get_count();
++c1; //increment c1
++c2; //increment c2
++c2; //increment c2
cout << “nc1=” << c1.get_count(); //display again
cout << “nc2=” << c2.get_count() << endl;
return 0;
}
Output
c1=0 ← counts are initially 0
c2=0
c1=1 ← incremented once
c2=2 ←incremented twice
Overloading Unary Operators
Operator Return Values
void operator ++ () //increment (prefix)
{
++count;
}
Counter c1, c2;
c1 = ++c2; //
Error
Operator Return Values
class Counter
{
private:
unsigned int count; //count
public:
Counter() : count(0) //constructor
{ }
unsigned int get_count() //return count
{ return count; }
Counter operator ++ () //increment count
{
++count; //increment count
Counter temp; //make a temporary Counter
temp.count = count; //give it same value as this obj
return temp; //return the copy
}
};
Operator Return Values
int main()
{
Counter c1, c2; //c1=0, c2=0
cout << “nc1=” << c1.get_count(); //display
cout << “nc2=” << c2.get_count();
++c1; //c1=1
c2 = ++c1; //c1=2, c2=2
cout << “nc1=” << c1.get_count(); //display again
cout << “nc2=” << c2.get_count() << endl;
return 0;
}
Output
c1=0
c2=0
c1=2
c2=2
Nameless Temporary Objects
class Counter
{
private:
unsigned int count; //count
public:
Counter() : count(0) //constructor no args
{ }
Counter(int c) : count(c) //constructor, one arg
{ }
unsigned int get_count() //return count
{ return count; }
Counter operator ++ () //increment count
{
++count; // increment count, then return
return Counter(count); // an unnamed temporary object
} // initialized to this count
};
int main()
{
Counter c1, c2; //c1=0, c2=0
cout << “nc1=” << c1.get_count(); //display
cout << “nc2=” << c2.get_count();
++c1; //c1=1
c2 = ++c1; //c1=2, c2=2
cout << “nc1=” << c1.get_count(); //display again
cout << “nc2=” << c2.get_count() << endl;
return 0;
}
Output
c1=0
c2=0
c1=2
c2=2
Nameless Temporary Objects
class Counter
{
private:
unsigned int count; //count
public:
Counter() : count(0) //constructor no args
{ }
Counter(int c) : count(c) //constructor, one arg
{ }
unsigned int get_count() const //return count
{ return count; }
Counter operator ++ () //increment count (prefix)
{ //increment count, then return
return Counter(++count); //an unnamed temporary object
} //initialized to this count
Counter operator ++ (int) //increment count (postfix)
{ //return an unnamed temporary
return Counter(count++); //object initialized to this
} //count, then increment count
};
Postfix Notation
int main()
{
Counter c1, c2; //c1=0, c2=0
cout << “nc1=” << c1.get_count(); //display
cout << “nc2=” << c2.get_count();
++c1; //c1=1
c2 = ++c1; //c1=2, c2=2 (prefix)
cout << “nc1=” << c1.get_count(); //display
cout << “nc2=” << c2.get_count();
c2 = c1++; //c1=3, c2=2 (postfix)
cout << “nc1=” << c1.get_count(); //display again
cout << “nc2=” << c2.get_count() << endl;
return 0;
}
Postfix Notation
Output
c1=0
c2=0
c1=2
c2=2
c1=3
c2=2
Arithmetic Operators
class Distance //English Distance class
{
private: int feet; float inches;
public: //constructor (no args)
Distance() : feet(0), inches(0.0)
{ } //constructor (two args)
Distance(int ft, float in) : feet(ft), inches(in)
{ }
void getdist() //get length from user
{
cout << “nEnter feet: “; cin >> feet;
cout << “Enter inches: “; cin >> inches;
}
void showdist() const //display distance
{ cout << feet << “’-” << inches << ‘”’; }
Distance operator + ( Distance ); //add 2 distances
};
Overloading Binary Operators
Distance Distance::operator + (Distance d2) //return sum
{
int f = feet + d2.feet; //add the feet
float i = inches + d2.inches; //add the inches
if(i >= 12.0) //if total exceeds 12.0,
{ //then decrease inches
i -= 12.0; //by 12.0 and
f++; //increase feet by 1
} //return a temporary Distance
return Distance(f,i); //initialized to sum
}
Overloading Binary Operators
int main()
{
Distance dist1, dist3; //define distances
dist1.getdist(); //get dist1 from user
Distance dist2(11, 6.25); //define, initialize dist2
dist3 = dist1 + dist2; //single ‘+’ operator
//display all lengths
cout << “dist1 = “; dist1.showdist(); cout << endl;
cout << “dist2 = “; dist2.showdist(); cout << endl;
cout << “dist3 = “; dist3.showdist(); cout << endl;
return 0;
}
Overloading Binary Operators
Output
Enter feet: 10
Enter inches: 6.5
dist1 = 10’-6.5” ← from user
dist2 = 11’-6.25” ← initialized in program
dist3 = 22’-0.75” ← dist1+dist2
dist3 = dist1 + dist2;
Overloading Binary Operators
Comparison Operators
bool operator < (Distance d2)
{
float bf1 = feet + inches/12;
float bf2 = d2.feet + d2.inches/12;
return (bf1 < bf2) ? true : false;
}
Operator overloading restrictions
• The following operators cannot be overloaded
– the member access or dot operator (.)
– the scope resolution operator (::)
– the conditional operator (?:)
– the pointer-to-member operator (->)
• One can’t create new operators ,only existing
operators can be overloaded
Ad

More Related Content

Similar to Mastering Operator Overloading in C++... (20)

C++ TUTORIAL 4
C++ TUTORIAL 4C++ TUTORIAL 4
C++ TUTORIAL 4
Farhan Ab Rahman
 
#ifndef RATIONAL_H   if this compiler macro is not defined #def.pdf
#ifndef RATIONAL_H    if this compiler macro is not defined #def.pdf#ifndef RATIONAL_H    if this compiler macro is not defined #def.pdf
#ifndef RATIONAL_H   if this compiler macro is not defined #def.pdf
exxonzone
 
12
1212
12
Pandiya Rajan
 
Class ‘increment’
Class ‘increment’Class ‘increment’
Class ‘increment’
Syed Zaid Irshad
 
Functions in C++ programming language.pptx
Functions in  C++ programming language.pptxFunctions in  C++ programming language.pptx
Functions in C++ programming language.pptx
rebin5725
 
C++ L05-Functions
C++ L05-FunctionsC++ L05-Functions
C++ L05-Functions
Mohammad Shaker
 
Assignement of programming & problem solving ass.(3)
Assignement of programming & problem solving ass.(3)Assignement of programming & problem solving ass.(3)
Assignement of programming & problem solving ass.(3)
Syed Umair
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
zindadili
 
Pro.docx
Pro.docxPro.docx
Pro.docx
ChantellPantoja184
 
Object Oriented Programming using C++: Ch09 Inheritance.pptx
Object Oriented Programming using C++: Ch09 Inheritance.pptxObject Oriented Programming using C++: Ch09 Inheritance.pptx
Object Oriented Programming using C++: Ch09 Inheritance.pptx
RashidFaridChishti
 
pointers.pptx
pointers.pptxpointers.pptx
pointers.pptx
MuhammadAbubakar680442
 
C++ normal assignments by maharshi_jd.pdf
C++ normal assignments by maharshi_jd.pdfC++ normal assignments by maharshi_jd.pdf
C++ normal assignments by maharshi_jd.pdf
maharshi1731
 
Lec 2.pptx programing errors \basic of programing
Lec 2.pptx programing errors \basic of programingLec 2.pptx programing errors \basic of programing
Lec 2.pptx programing errors \basic of programing
daoodkhan4177
 
Final DAA_prints.pdf
Final DAA_prints.pdfFinal DAA_prints.pdf
Final DAA_prints.pdf
Yashpatel821746
 
7720
77207720
7720
Yashpatel821746
 
C++ TUTORIAL 2
C++ TUTORIAL 2C++ TUTORIAL 2
C++ TUTORIAL 2
Farhan Ab Rahman
 
Pointers in c++ programming presentation
Pointers in c++ programming presentationPointers in c++ programming presentation
Pointers in c++ programming presentation
SourabhGour9
 
Chainer-Compiler 動かしてみた
Chainer-Compiler 動かしてみたChainer-Compiler 動かしてみた
Chainer-Compiler 動かしてみた
Akira Maruoka
 
Tugas praktikukm pemrograman c++
Tugas praktikukm  pemrograman c++Tugas praktikukm  pemrograman c++
Tugas praktikukm pemrograman c++
Dendi Riadi
 
Modify the Time classattached to be able to work with Date.pdf
Modify the Time classattached to be able to work with Date.pdfModify the Time classattached to be able to work with Date.pdf
Modify the Time classattached to be able to work with Date.pdf
aaseletronics2013
 
#ifndef RATIONAL_H   if this compiler macro is not defined #def.pdf
#ifndef RATIONAL_H    if this compiler macro is not defined #def.pdf#ifndef RATIONAL_H    if this compiler macro is not defined #def.pdf
#ifndef RATIONAL_H   if this compiler macro is not defined #def.pdf
exxonzone
 
Functions in C++ programming language.pptx
Functions in  C++ programming language.pptxFunctions in  C++ programming language.pptx
Functions in C++ programming language.pptx
rebin5725
 
Assignement of programming & problem solving ass.(3)
Assignement of programming & problem solving ass.(3)Assignement of programming & problem solving ass.(3)
Assignement of programming & problem solving ass.(3)
Syed Umair
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
zindadili
 
Object Oriented Programming using C++: Ch09 Inheritance.pptx
Object Oriented Programming using C++: Ch09 Inheritance.pptxObject Oriented Programming using C++: Ch09 Inheritance.pptx
Object Oriented Programming using C++: Ch09 Inheritance.pptx
RashidFaridChishti
 
C++ normal assignments by maharshi_jd.pdf
C++ normal assignments by maharshi_jd.pdfC++ normal assignments by maharshi_jd.pdf
C++ normal assignments by maharshi_jd.pdf
maharshi1731
 
Lec 2.pptx programing errors \basic of programing
Lec 2.pptx programing errors \basic of programingLec 2.pptx programing errors \basic of programing
Lec 2.pptx programing errors \basic of programing
daoodkhan4177
 
Pointers in c++ programming presentation
Pointers in c++ programming presentationPointers in c++ programming presentation
Pointers in c++ programming presentation
SourabhGour9
 
Chainer-Compiler 動かしてみた
Chainer-Compiler 動かしてみたChainer-Compiler 動かしてみた
Chainer-Compiler 動かしてみた
Akira Maruoka
 
Tugas praktikukm pemrograman c++
Tugas praktikukm  pemrograman c++Tugas praktikukm  pemrograman c++
Tugas praktikukm pemrograman c++
Dendi Riadi
 
Modify the Time classattached to be able to work with Date.pdf
Modify the Time classattached to be able to work with Date.pdfModify the Time classattached to be able to work with Date.pdf
Modify the Time classattached to be able to work with Date.pdf
aaseletronics2013
 

Recently uploaded (20)

Study in Pink (forensic case study of Death)
Study in Pink (forensic case study of Death)Study in Pink (forensic case study of Death)
Study in Pink (forensic case study of Death)
memesologiesxd
 
Euclid: The Story So far, a Departmental Colloquium at Maynooth University
Euclid: The Story So far, a Departmental Colloquium at Maynooth UniversityEuclid: The Story So far, a Departmental Colloquium at Maynooth University
Euclid: The Story So far, a Departmental Colloquium at Maynooth University
Peter Coles
 
Mycology:Characteristics of Ascomycetes Fungi
Mycology:Characteristics of Ascomycetes FungiMycology:Characteristics of Ascomycetes Fungi
Mycology:Characteristics of Ascomycetes Fungi
SAYANTANMALLICK5
 
Secondary metabolite ,Plants and Health Care
Secondary metabolite ,Plants and Health CareSecondary metabolite ,Plants and Health Care
Secondary metabolite ,Plants and Health Care
Nistarini College, Purulia (W.B) India
 
CORONARY ARTERY BYPASS GRAFTING (1).pptx
CORONARY ARTERY BYPASS GRAFTING (1).pptxCORONARY ARTERY BYPASS GRAFTING (1).pptx
CORONARY ARTERY BYPASS GRAFTING (1).pptx
DharaniJajula
 
Eric Schott- Environment, Animal and Human Health (3).pptx
Eric Schott- Environment, Animal and Human Health (3).pptxEric Schott- Environment, Animal and Human Health (3).pptx
Eric Schott- Environment, Animal and Human Health (3).pptx
ttalbert1
 
Cleaned_Expanded_Metal_Nanoparticles_Presentation.pptx
Cleaned_Expanded_Metal_Nanoparticles_Presentation.pptxCleaned_Expanded_Metal_Nanoparticles_Presentation.pptx
Cleaned_Expanded_Metal_Nanoparticles_Presentation.pptx
zainab98aug
 
SULPHONAMIDES AND SULFONES Medicinal Chemistry III.ppt
SULPHONAMIDES AND SULFONES Medicinal Chemistry III.pptSULPHONAMIDES AND SULFONES Medicinal Chemistry III.ppt
SULPHONAMIDES AND SULFONES Medicinal Chemistry III.ppt
HRUTUJA WAGH
 
Issues in using AI in academic publishing.pdf
Issues in using AI in academic publishing.pdfIssues in using AI in academic publishing.pdf
Issues in using AI in academic publishing.pdf
Angelo Salatino
 
The Microbial World. Microbiology , Microbes, infections
The Microbial World. Microbiology , Microbes, infectionsThe Microbial World. Microbiology , Microbes, infections
The Microbial World. Microbiology , Microbes, infections
NABIHANAEEM2
 
Somato_Sensory _ somatomotor_Nervous_System.pptx
Somato_Sensory _ somatomotor_Nervous_System.pptxSomato_Sensory _ somatomotor_Nervous_System.pptx
Somato_Sensory _ somatomotor_Nervous_System.pptx
klynct
 
Animal Models for Biological and Clinical Research ppt 2.pptx
Animal Models for Biological and Clinical Research ppt 2.pptxAnimal Models for Biological and Clinical Research ppt 2.pptx
Animal Models for Biological and Clinical Research ppt 2.pptx
MahitaLaveti
 
Discrete choice experiments: Environmental Improvements to Airthrey Loch Lake...
Discrete choice experiments: Environmental Improvements to Airthrey Loch Lake...Discrete choice experiments: Environmental Improvements to Airthrey Loch Lake...
Discrete choice experiments: Environmental Improvements to Airthrey Loch Lake...
Professional Content Writing's
 
Carboxylic-Acid-Derivatives.lecture.presentation
Carboxylic-Acid-Derivatives.lecture.presentationCarboxylic-Acid-Derivatives.lecture.presentation
Carboxylic-Acid-Derivatives.lecture.presentation
GLAEXISAJULGA
 
Antimalarial drug Medicinal Chemistry III
Antimalarial drug Medicinal Chemistry IIIAntimalarial drug Medicinal Chemistry III
Antimalarial drug Medicinal Chemistry III
HRUTUJA WAGH
 
Preclinical Advances in Nuclear Neurology.pptx
Preclinical Advances in Nuclear Neurology.pptxPreclinical Advances in Nuclear Neurology.pptx
Preclinical Advances in Nuclear Neurology.pptx
MahitaLaveti
 
An upper limit to the lifetime of stellar remnants from gravitational pair pr...
An upper limit to the lifetime of stellar remnants from gravitational pair pr...An upper limit to the lifetime of stellar remnants from gravitational pair pr...
An upper limit to the lifetime of stellar remnants from gravitational pair pr...
Sérgio Sacani
 
Applications of Radioisotopes in Cancer Research.pptx
Applications of Radioisotopes in Cancer Research.pptxApplications of Radioisotopes in Cancer Research.pptx
Applications of Radioisotopes in Cancer Research.pptx
MahitaLaveti
 
Freshwater Biome Types, Characteristics and Factors
Freshwater Biome Types, Characteristics and FactorsFreshwater Biome Types, Characteristics and Factors
Freshwater Biome Types, Characteristics and Factors
mytriplemonlineshop
 
ICAI OpenGov Lab: A Quick Introduction | AI for Open Government
ICAI OpenGov Lab: A Quick Introduction | AI for Open GovernmentICAI OpenGov Lab: A Quick Introduction | AI for Open Government
ICAI OpenGov Lab: A Quick Introduction | AI for Open Government
David Graus
 
Study in Pink (forensic case study of Death)
Study in Pink (forensic case study of Death)Study in Pink (forensic case study of Death)
Study in Pink (forensic case study of Death)
memesologiesxd
 
Euclid: The Story So far, a Departmental Colloquium at Maynooth University
Euclid: The Story So far, a Departmental Colloquium at Maynooth UniversityEuclid: The Story So far, a Departmental Colloquium at Maynooth University
Euclid: The Story So far, a Departmental Colloquium at Maynooth University
Peter Coles
 
Mycology:Characteristics of Ascomycetes Fungi
Mycology:Characteristics of Ascomycetes FungiMycology:Characteristics of Ascomycetes Fungi
Mycology:Characteristics of Ascomycetes Fungi
SAYANTANMALLICK5
 
CORONARY ARTERY BYPASS GRAFTING (1).pptx
CORONARY ARTERY BYPASS GRAFTING (1).pptxCORONARY ARTERY BYPASS GRAFTING (1).pptx
CORONARY ARTERY BYPASS GRAFTING (1).pptx
DharaniJajula
 
Eric Schott- Environment, Animal and Human Health (3).pptx
Eric Schott- Environment, Animal and Human Health (3).pptxEric Schott- Environment, Animal and Human Health (3).pptx
Eric Schott- Environment, Animal and Human Health (3).pptx
ttalbert1
 
Cleaned_Expanded_Metal_Nanoparticles_Presentation.pptx
Cleaned_Expanded_Metal_Nanoparticles_Presentation.pptxCleaned_Expanded_Metal_Nanoparticles_Presentation.pptx
Cleaned_Expanded_Metal_Nanoparticles_Presentation.pptx
zainab98aug
 
SULPHONAMIDES AND SULFONES Medicinal Chemistry III.ppt
SULPHONAMIDES AND SULFONES Medicinal Chemistry III.pptSULPHONAMIDES AND SULFONES Medicinal Chemistry III.ppt
SULPHONAMIDES AND SULFONES Medicinal Chemistry III.ppt
HRUTUJA WAGH
 
Issues in using AI in academic publishing.pdf
Issues in using AI in academic publishing.pdfIssues in using AI in academic publishing.pdf
Issues in using AI in academic publishing.pdf
Angelo Salatino
 
The Microbial World. Microbiology , Microbes, infections
The Microbial World. Microbiology , Microbes, infectionsThe Microbial World. Microbiology , Microbes, infections
The Microbial World. Microbiology , Microbes, infections
NABIHANAEEM2
 
Somato_Sensory _ somatomotor_Nervous_System.pptx
Somato_Sensory _ somatomotor_Nervous_System.pptxSomato_Sensory _ somatomotor_Nervous_System.pptx
Somato_Sensory _ somatomotor_Nervous_System.pptx
klynct
 
Animal Models for Biological and Clinical Research ppt 2.pptx
Animal Models for Biological and Clinical Research ppt 2.pptxAnimal Models for Biological and Clinical Research ppt 2.pptx
Animal Models for Biological and Clinical Research ppt 2.pptx
MahitaLaveti
 
Discrete choice experiments: Environmental Improvements to Airthrey Loch Lake...
Discrete choice experiments: Environmental Improvements to Airthrey Loch Lake...Discrete choice experiments: Environmental Improvements to Airthrey Loch Lake...
Discrete choice experiments: Environmental Improvements to Airthrey Loch Lake...
Professional Content Writing's
 
Carboxylic-Acid-Derivatives.lecture.presentation
Carboxylic-Acid-Derivatives.lecture.presentationCarboxylic-Acid-Derivatives.lecture.presentation
Carboxylic-Acid-Derivatives.lecture.presentation
GLAEXISAJULGA
 
Antimalarial drug Medicinal Chemistry III
Antimalarial drug Medicinal Chemistry IIIAntimalarial drug Medicinal Chemistry III
Antimalarial drug Medicinal Chemistry III
HRUTUJA WAGH
 
Preclinical Advances in Nuclear Neurology.pptx
Preclinical Advances in Nuclear Neurology.pptxPreclinical Advances in Nuclear Neurology.pptx
Preclinical Advances in Nuclear Neurology.pptx
MahitaLaveti
 
An upper limit to the lifetime of stellar remnants from gravitational pair pr...
An upper limit to the lifetime of stellar remnants from gravitational pair pr...An upper limit to the lifetime of stellar remnants from gravitational pair pr...
An upper limit to the lifetime of stellar remnants from gravitational pair pr...
Sérgio Sacani
 
Applications of Radioisotopes in Cancer Research.pptx
Applications of Radioisotopes in Cancer Research.pptxApplications of Radioisotopes in Cancer Research.pptx
Applications of Radioisotopes in Cancer Research.pptx
MahitaLaveti
 
Freshwater Biome Types, Characteristics and Factors
Freshwater Biome Types, Characteristics and FactorsFreshwater Biome Types, Characteristics and Factors
Freshwater Biome Types, Characteristics and Factors
mytriplemonlineshop
 
ICAI OpenGov Lab: A Quick Introduction | AI for Open Government
ICAI OpenGov Lab: A Quick Introduction | AI for Open GovernmentICAI OpenGov Lab: A Quick Introduction | AI for Open Government
ICAI OpenGov Lab: A Quick Introduction | AI for Open Government
David Graus
 
Ad

Mastering Operator Overloading in C++...

  • 2. Overloading Unary Operators // countpp1.cpp // increment counter variable with ++ operator #include <iostream> using namespace std; ///////////////////////////////////////////////////////////// /// class Counter { private: unsigned int count; //count public: Counter() : count(0) //constructor { } unsigned int get_count() //return count { return count; } void operator ++ () //increment (prefix) { ++count; } }; Keyword
  • 3. Overloading Unary Operators int main() { Counter c1, c2; //define and initialize cout << “nc1=” << c1.get_count(); //display cout << “nc2=” << c2.get_count(); ++c1; //increment c1 ++c2; //increment c2 ++c2; //increment c2 cout << “nc1=” << c1.get_count(); //display again cout << “nc2=” << c2.get_count() << endl; return 0; } Output c1=0 ← counts are initially 0 c2=0 c1=1 ← incremented once c2=2 ←incremented twice
  • 5. Operator Return Values void operator ++ () //increment (prefix) { ++count; } Counter c1, c2; c1 = ++c2; // Error
  • 6. Operator Return Values class Counter { private: unsigned int count; //count public: Counter() : count(0) //constructor { } unsigned int get_count() //return count { return count; } Counter operator ++ () //increment count { ++count; //increment count Counter temp; //make a temporary Counter temp.count = count; //give it same value as this obj return temp; //return the copy } };
  • 7. Operator Return Values int main() { Counter c1, c2; //c1=0, c2=0 cout << “nc1=” << c1.get_count(); //display cout << “nc2=” << c2.get_count(); ++c1; //c1=1 c2 = ++c1; //c1=2, c2=2 cout << “nc1=” << c1.get_count(); //display again cout << “nc2=” << c2.get_count() << endl; return 0; } Output c1=0 c2=0 c1=2 c2=2
  • 8. Nameless Temporary Objects class Counter { private: unsigned int count; //count public: Counter() : count(0) //constructor no args { } Counter(int c) : count(c) //constructor, one arg { } unsigned int get_count() //return count { return count; } Counter operator ++ () //increment count { ++count; // increment count, then return return Counter(count); // an unnamed temporary object } // initialized to this count };
  • 9. int main() { Counter c1, c2; //c1=0, c2=0 cout << “nc1=” << c1.get_count(); //display cout << “nc2=” << c2.get_count(); ++c1; //c1=1 c2 = ++c1; //c1=2, c2=2 cout << “nc1=” << c1.get_count(); //display again cout << “nc2=” << c2.get_count() << endl; return 0; } Output c1=0 c2=0 c1=2 c2=2 Nameless Temporary Objects
  • 10. class Counter { private: unsigned int count; //count public: Counter() : count(0) //constructor no args { } Counter(int c) : count(c) //constructor, one arg { } unsigned int get_count() const //return count { return count; } Counter operator ++ () //increment count (prefix) { //increment count, then return return Counter(++count); //an unnamed temporary object } //initialized to this count Counter operator ++ (int) //increment count (postfix) { //return an unnamed temporary return Counter(count++); //object initialized to this } //count, then increment count }; Postfix Notation
  • 11. int main() { Counter c1, c2; //c1=0, c2=0 cout << “nc1=” << c1.get_count(); //display cout << “nc2=” << c2.get_count(); ++c1; //c1=1 c2 = ++c1; //c1=2, c2=2 (prefix) cout << “nc1=” << c1.get_count(); //display cout << “nc2=” << c2.get_count(); c2 = c1++; //c1=3, c2=2 (postfix) cout << “nc1=” << c1.get_count(); //display again cout << “nc2=” << c2.get_count() << endl; return 0; } Postfix Notation Output c1=0 c2=0 c1=2 c2=2 c1=3 c2=2
  • 12. Arithmetic Operators class Distance //English Distance class { private: int feet; float inches; public: //constructor (no args) Distance() : feet(0), inches(0.0) { } //constructor (two args) Distance(int ft, float in) : feet(ft), inches(in) { } void getdist() //get length from user { cout << “nEnter feet: “; cin >> feet; cout << “Enter inches: “; cin >> inches; } void showdist() const //display distance { cout << feet << “’-” << inches << ‘”’; } Distance operator + ( Distance ); //add 2 distances }; Overloading Binary Operators
  • 13. Distance Distance::operator + (Distance d2) //return sum { int f = feet + d2.feet; //add the feet float i = inches + d2.inches; //add the inches if(i >= 12.0) //if total exceeds 12.0, { //then decrease inches i -= 12.0; //by 12.0 and f++; //increase feet by 1 } //return a temporary Distance return Distance(f,i); //initialized to sum } Overloading Binary Operators
  • 14. int main() { Distance dist1, dist3; //define distances dist1.getdist(); //get dist1 from user Distance dist2(11, 6.25); //define, initialize dist2 dist3 = dist1 + dist2; //single ‘+’ operator //display all lengths cout << “dist1 = “; dist1.showdist(); cout << endl; cout << “dist2 = “; dist2.showdist(); cout << endl; cout << “dist3 = “; dist3.showdist(); cout << endl; return 0; } Overloading Binary Operators Output Enter feet: 10 Enter inches: 6.5 dist1 = 10’-6.5” ← from user dist2 = 11’-6.25” ← initialized in program dist3 = 22’-0.75” ← dist1+dist2
  • 15. dist3 = dist1 + dist2; Overloading Binary Operators
  • 16. Comparison Operators bool operator < (Distance d2) { float bf1 = feet + inches/12; float bf2 = d2.feet + d2.inches/12; return (bf1 < bf2) ? true : false; }
  • 17. Operator overloading restrictions • The following operators cannot be overloaded – the member access or dot operator (.) – the scope resolution operator (::) – the conditional operator (?:) – the pointer-to-member operator (->) • One can’t create new operators ,only existing operators can be overloaded
  翻译: