-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctors_example.cpp
More file actions
64 lines (41 loc) · 1.01 KB
/
functors_example.cpp
File metadata and controls
64 lines (41 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
//Abstract base calss (it cannot be instantiated as it its abstract class)
class BinaryFunction{
public:
BinaryFunction(){};
virtual double operator() (double left, double right) = 0;
};
//Add two doubles
class Add : public BinaryFunction{
public:
Add(){};
virtual double operator() (double left, double right) {
return left+right;
}
};
class Multiply : public BinaryFunction{
public:
Multiply(){};
virtual double operator() (double left, double right) {
return left*right;
}
};
//Now we define a custom function
double binary_op(double left, double right, BinaryFunction* bin_func)
{
return (*bin_func)(left,right);
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
double a= 5.0;
double b = 10.0;
BinaryFunction *pAdd = new Add();
BinaryFunction *pMultiply = new Multiply();
std::cout<<"Add: "<<binary_op(a,b,pAdd)<<std::endl;
std::cout<<"Add: "<<binary_op(a,b,pMultiply)<<std::endl;
return 0;
}