Write a program to design a class complex to represent negative numbers. The negative class
should use an external function (use it as friend function) to add two negative numbers. The
function should return an object of type negative representing the sum of two negative
numbers.
#include <iostream>
using namespace std;
class Negative
{
private:
double neg;
public:
Negative(double a=0)
{
this->neg=a;
}
Negative(const Negative&n)
{
this->neg=n.getData();
}
double getData()const
{
return this->neg;
}
void setData(double d)
{
this->neg=d;
}
friend Negative operator+(const Negative& a,const Negative&b);
friend ostream& operator<<(ostream& os,const Negative& n);
friend istream& operator>>(ostream& is,Negative& n);
};
Negative operator+(const Negative& a,const Negative&b)
{
Negative ans(a.getData()+b.getData());
return ans;
}
ostream& operator<<(ostream& os,const Negative& n)
{
os<<n.getData();
return os;
}
istream& operator>>(istream& is,Negative& n)
{
cout<<"Please input negative number: ";
double d;
is>>d;
n.setData(d);
return is;
}
int main() {
Negative a(-50);
Negative b(-23);
cin>>a;
cin>>b;
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
cout<<"a+b="<<a+b<<endl;
return 0;
}
Comments
Leave a comment