View Full Version : Returning Object


S.Tarafdar
08-11-03, 03:37 AM
I have this c++ code:

#include&ltiostream&gt
using namespace std;

class Complex{
float real;
float imaginary;
public:
void getvalue(float,float);
void putvalue();
Complex sum(Complex,Complex);
};

void Complex::getvalue(float re,float im){
real=re;
imaginary=im;
}

void Complex::putvalue(){
cout&lt&ltreal&lt&lt"+j"&lt&ltimaginary&lt&ltendl;
}

Complex Complex:: sum(Complex x,Complex y){
Complex p;
p.real=x.real+y.real;
p.imaginary=x.imaginary+y.imaginary;

return p;
}

int main(){
Complex x,y,z;
x.getvalue(2,8);
y.getvalue(4,9);
z=sum(x,y);
z.putvalue();

return 0;
}


I want to return p from 'sum' method.But the compiler shows error.Please suggest.

okinrus
08-11-03, 04:53 PM
I think you want to do

#include<iostream>
using namespace std;

class Complex{
float real;
float imaginary;
public:
void getvalue(float,float);
void putvalue();
static Complex sum(Complex,Complex);
};


Complex Complex::sum(Complex x,Complex y){
Complex p;
p.real=x.real+y.real;
p.imaginary=x.imaginary+y.imaginary;

return p;
}

//....

int main(){
Complex x,y,z;
x.getvalue(2,8);
y.getvalue(4,9);
z = Complex::sum(x,y);
z.putvalue();

return 0;
}

bigjnorman
08-28-03, 07:38 PM
learning how to use pointers and templates will save you a lot of pain and suffering when it comes to problems like those.

go here:
http://www.cprogramming.com/tutorial.html