680 Overloading
680 Overloading
Ben Langmead
[email protected]
www.langmead-lab.org
#include <iostream>
int main() {
output_type(1); // int argument
output_type(1.f); // float argument
return 0;
}
2
Overloading
3
Overloading
#include <iostream>
int main() {
int i = get_one();
float f = get_one();
cout << i << ' ' << f << endl;
return 0;
}
4
Overloading
5
Operator overloading
6
Operator overloading
7
Operator overloading
#include <iostream>
#include <vector>
int main() {
vector<int> vec = {1, 2, 3};
cout << vec << endl;
return 0;
}
8
Operator overloading
int main() {
const vector<int> vec = {1, 2, 3};
cout << vec << endl; // now this will work!
return 0;
}
10
Operator overloading
11
Operator overloading
12
Operator overloading
private:
double real, imaginary;
};
15
Operator overloading
class Complex {
public:
...
private:
double real, imaginary;
};
16
Operator overloading
17
Operator overloading
class Complex {
public:
...
private:
double real, imaginary;
};
18
Operator overloading
class Complex {
public:
...
friend std::ostream& operator<<(std::ostream& os, Complex c);
...
};
19
Operator overloading
Same-class
Derived-class members &
Access modifier Any function members friends
20
Operator overloading
int c = 0;
c += (c += 2);
21
Operator overloading
22
Operator overloading
class Complex {
public:
...
Complex operator+=(const Complex& rhs) {
real += rhs.real;
imaginary += rhs.imaginary;
return *this;
}
...
};
23
Operator overloading
+ - * / % ^ & | ~
! -> = < > <= >= ++ --
<< >> == != && || += -= /=
%= ^= &= |= *= <<= >>= [] ()
24
Operator overloading
25
Operator overloading
class Date {
public:
...
bool operator<(const Date& rhs) const {
if(year < rhs.year) return true;
if(year > rhs.year) return false;
if(month < rhs.month) return true;
if(month > rhs.month) return false;
return day < rhs.day;
}
...
};
26