-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoverload-op.cpp
48 lines (39 loc) · 1.13 KB
/
overload-op.cpp
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
// This example illustrates overloading the plus (+) operator.
#include <iostream>
using namespace std;
class complx
{
double real,
imag;
public:
complx( double real = 0., double imag = 0.); // constructor
complx operator+(const complx&) const; // operator+()
void print();
};
// define constructor
complx::complx( double r, double i )
{
real = r; imag = i;
}
// define overloaded + (plus) operator
complx complx::operator+ (const complx& c) const
{
complx result;
cout << "complx::operator+ this=" << this->real << "," << this->imag << endl;
cout << "complx::operator+ c=" << c.real << "," << c.imag << endl;
cout << endl;
result.real = (this->real + c.real);
result.imag = (this->imag + c.imag);
return result;
}
// define print method
void complx::print() { std::cout << "(" << real << "," << imag << ")"; }
int main()
{
complx x(4,4);
complx y(6,6);
complx z = x + y; // calls complx::operator+()
cout << "x="; x.print(); cout << "\n";
cout << "y="; y.print(); cout << "\n";
cout << "z="; z.print(); cout << "\n";
}