//class Distance with m and cm as members
#include <iostream>
using namespace std;
class Distance
{
int m,cm;
public:
void read()
{
cout<<"Enter m and cm: ";
cin>>m>>cm;
}
void display()
{
cout<<m<<"m "<<cm<<"cm"<<endl;
}
friend Distance operator+(Distance d1,Distance d2) //friend function
{
Distance dist;
dist.m=d1.m+d2.m;
dist.cm=d1.cm+d2.cm;
if(dist.cm>=100)
{
dist.cm-=100;
dist.m++;
}
return dist;
}
};
int main()
{
Distance d1,d2,d3;
d1.read();
d2.read();
d3=d1+d2; //same as operator+(d1,d2);
d1.display();
d2.display();
d3.display();
return 0;
}
#include <iostream>
using namespace std;
class Distance
{
int m,cm;
public:
void read()
{
cout<<"Enter m and cm: ";
cin>>m>>cm;
}
void display()
{
cout<<m<<"m "<<cm<<"cm"<<endl;
}
friend Distance operator+(Distance d1,Distance d2) //friend function
{
Distance dist;
dist.m=d1.m+d2.m;
dist.cm=d1.cm+d2.cm;
if(dist.cm>=100)
{
dist.cm-=100;
dist.m++;
}
return dist;
}
};
int main()
{
Distance d1,d2,d3;
d1.read();
d2.read();
d3=d1+d2; //same as operator+(d1,d2);
d1.display();
d2.display();
d3.display();
return 0;
}
No comments:
Post a Comment