3/28/2016

Overloading,friend function,constructor,destructor(mixing operations in c++ )

A program which contents class complex,constructor,destructor,friend function sum,overload arithmetic operators(+ and -).This program accepts two complex numbers and adds or subtracts these two complex number.


#include<iostream>
using namespace std;
class complex
{
public:
float real;
float imag;

complex()
{
real=0;
imag=0;
}

~complex()
{
real=0;
imag=0;
}

complex operator + (complex bbb)
{
complex operation;
operation.real=real+bbb.real;
operation.imag=imag+bbb.imag;
return(operation);
}
complex operator - (complex bbb)
{
complex operation;
operation.real=real-bbb.real;
operation.imag=imag-bbb.imag;
return(operation);
}

void friend sum(complex a,complex b)
{
cout<<a.real;
if(b.imag<0)
{
cout<<"-i"<<(-1)*b.imag;
}
else
{
cout<<"+i"<<b.imag;
}
}
};

int main()
{
int i=0;
char ch;
complex aaa,bbb,operation;
cout<<"Enter first complex no.";
cin>>aaa.real;
cin>>aaa.imag;
cout<<"First complex no.:\n";
sum(aaa,aaa);
cout<<"\nEnter second complex no.";
cin>>bbb.real;
cin>>bbb.imag;
cout<<"Second complex no.:\n"
sum(bbb,bbb);
cout<<"\nSummation:-a\nSubtraction:-b\n";
cin>>ch;
switch(ch)
{
case 'a':
operation=aaa+bbb;
cout<<"\nSummation of two complex no.:\n";

break;

case 'b':
operation=aaa-bbb;
cout<<"Subtraction of two complex no.:\n";

break;
}
sum(operation,operation);
return 0;
}

Output:
Enter fiest complex no.5 -9
First complex no.:
5-i9
Enter second complex no.4 -2
Second complex no.:
4-i2
Summation:-a
Subtration:-b
a
Summation of two complex no.:
9-i11

………………………………………………………
A program using friend function join,overloading assignment operator (=),constructor,destructor.This program accepts two string and joins them.

#include<iostream>
using namespace std;
class str
{
public:
str(){}
~str(){}
char a[50];
void enter()
{
cin>>a;
}

str operator = (str test)
{
for(i=0;i<=49;i++)
{
a[i]=test.a[i];
}
}

void print()
{
cout<<a;
}

void friend join(str aaa,str bbb)
{
string b;
b=strcat(aaa.a,bbb.a);
cout<<"\n\nJoint string="<<b;
}
};

int main()
{
str aa,bb,cc;
cout<<"Enter fitst string:\n";
aa.enter();
bb.opetator= (aa);
cout<<"First string=";
bb.print();
cout<<"\nEnter second string:\n";
cc.enter();
bb.operator= (cc);
cout<<"Second string=";
bb.print();
join(aa,cc);
return 0;
}

Output:
Enter first string:
Very
First string=Very
Enter second string:
good
Second string=good

Joint string=Verygood


----------------------------------------------------------

SEARCH ALL PROGRAMMINGS AND TOPICS






No comments:

Post a Comment