







Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!








Operator overloading
Operator overloading makes theoperators have meaning appropriateto the new types
C++ does not allow new operators tobe created, but it does allow mostexisting operators to be overloaded.
Use of C++ build-in operators touser-defined class objects
Operator classification
class
Complex
{
public:
Complex();~Complex();void
printComplex()
const;
float
mag(); float
phase(); void
setComplex(float,
float);
float
getReal()
const;
float
getImag()
const;
void
setReal(float); void
setImag(float); Complex
operator+(Complex &);
private:
float
real; float
imag;
}; Complex Complex::operator+(Complex
&a)
{
Complex
temp; temp.real
=^
real
+^
a.real;
temp.imag
=^
imag
+^
a.imag;
return
temp;
}
int
main() {
Complex
number1,
number2, number3;
number1.setComplex(2,
3);
number2.setReal(-3);number2.setImag(2);//number3 = number1.operator+(number2);number
=^
number
+^
number2;
return
0;
}
class
Complex
{
public:
Complex();~Complex();void
printComplex()
const;
float
mag(); float
phase(); void
setComplex(float,
float);
float
getReal()
const;
float
getImag()
const;
void
setReal(float); void
setImag(float); Complex operator+(Complex);Complex
&operator++();
private:
float
real; float
imag;
};
Complex &Complex::operator++(){
real++;imag++;return
*this;
} int
main() {
Complex
number3; number3.setComplex(2,
3);
//number3.operator++();++number3;return
0;
}
The “friend” function
A^ friend
function of a class is defined outside that class’ scope, yet has the right to access
private
members of the class
// class definitionclass Complex {
friend void setRealf(Complex &, float); public:
Complex();Complex(float, float);~Complex();void
setReal(float); void
setImag(float);
private:
float real;float imag; };^
No^
class
scope
void setRealf(Complex &x, float a) {
x.real =
a;
} void
Complex::setReal(float a) {
real = a; }
//^
main ……Complex
number1; number1.setReal(1.0);setReaf(number1,
1.0);
……
Overloading steam I/O operators
//^
class
definition
class
Complex
{ friend
ostream
&^
operator<<(ostream
&,
Complex);
public:
Complex();Complex(float,
float);
~Complex();void
setComplex(float,
float);
void
printComplex(); float
getReal()
const;
float
getImag()
const;
void
setReal(float); void
setImag(float); Complex operator++(); private:
float
real; float
imag;
};^
ostream &
operator<<(ostream
&out,
Complex
a)
{
out
<<
a.real
<<
“+”
<<
a.imag
<<
“i”
<<
endl ;
return
out;
}
//^
main ……Complex
number1; number1.setComplex(1.0,
2.0);
//^
oprator<<(cout,
number1);
cout
<< number1; ……
What do you need to know? ^
Fundamentals ^
Pre-form ^
Post-form
^
Advanced ^