Click here to Skip to main content
13,593,048 members
Rate this:
 
Please Sign up or sign in to vote.
See more:
For example::
#include<iostream.h>
class ex
{
public:
ex()
{
a=0;
b=0;
}
ex(
..
...
}
};
void main()
{
ex e1(3,5), e2(5,7),e3;
e3=e1.add(e2);
}

The answer should be 8 q2..
The x of e1 should be added to x of e2....and y of e1 should be added to y of e2...
Thanks ... a s a p..

What I have tried:

I have tried but I didn't got it
Posted 14-Jun-18 8:59am
Updated 5 days ago
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

e3=e1.add(e2);
Seeing this statement and knowing that all applies to the class ex, the function prototype must be
ex add(const ex& e1) const;
and the corresponding implementation is
ex ex::add(const ex& e1) const
{
    ex result;
    result.a = this->a + e1.a;
    result.b = this->b + e1.b;
    return result;
}
or shorter using the constructor (and to be placed in the class definition)
ex add(const ex& e1) const
{
    return ex(this->a + e1.a, this->b + e1.b);
}
  Permalink  
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

There are (at least) two ways you can do this. You can make an add method as you have or you can make an addition operator. I would say the add method would best for you right now. Here's one way it can be done :
void ex::add( ex *pex1, ex *pex2 )
{
   x = pex1->x + pex2->x;
   y = pex1->y + pex2->y;
}
and to use it you would write :
e3.add( &e1, &e2 );
Normally I would use an operator or pass references to a function but I think passing pointers is the right thing for you to do at this stage of your experience.
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web02 | 2.8.180618.1 | Last Updated 15 Jun 2018
Copyright © CodeProject, 1999-2018
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100