Operator Overloading
// Operator Overloading
#include <iostream>
using namespace std;
class Complex
{
private:
float real;
float img;
public:
Complex()
{
real = img = 0;
}
Complex(float real, float img)
{
this->real = real;
this->img = img;
}
// Complex add(Complex c)
// {
// Complex tmp;
// tmp.real = this->real + c.real;
// tmp.img = this->img + c.img;
// return tmp;
// }
// Opertors which cannot be oberloaded
// ::, ., .*, ?:
Complex operator +(Complex c)
{
Complex tmp;
tmp.real = this->real + c.real;
tmp.img = this->img + c.img;
return tmp;
}
Complex operator -(Complex c)
{
Complex tmp;
tmp.real = this->real - c.real;
tmp.img = this->img - c.img;
return tmp;
}
void display()
{
cout << this->real << " + " << this->img << "i" << endl;
}
};
int main()
{
Complex c1(10.5, 20.5), c2(9.3, 3.5), c3;
// c3 = c1.add(c2);
c3 = c1 + c2;
c3.display();
c3 = c1 - c2; // 1.2 + 17i
c3.display();
return 0;
}
#include <iostream>
using namespace std;
class Complex
{
private:
float real;
float img;
public:
Complex()
{
real = img = 0;
}
Complex(float real, float img)
{
this->real = real;
this->img = img;
}
// Complex add(Complex c)
// {
// Complex tmp;
// tmp.real = this->real + c.real;
// tmp.img = this->img + c.img;
// return tmp;
// }
// Opertors which cannot be oberloaded
// ::, ., .*, ?:
Complex operator +(Complex c)
{
Complex tmp;
tmp.real = this->real + c.real;
tmp.img = this->img + c.img;
return tmp;
}
Complex operator -(Complex c)
{
Complex tmp;
tmp.real = this->real - c.real;
tmp.img = this->img - c.img;
return tmp;
}
void display()
{
cout << this->real << " + " << this->img << "i" << endl;
}
};
int main()
{
Complex c1(10.5, 20.5), c2(9.3, 3.5), c3;
// c3 = c1.add(c2);
c3 = c1 + c2;
c3.display();
c3 = c1 - c2; // 1.2 + 17i
c3.display();
return 0;
}
Comments
Post a Comment
Post Your Valuable Comments