the program is ok(i think)but the data is fixed.i want it able to input your own data.i tried cin>>c1.real>>c1.image;
cin>>c2.real>>c2.image;
but it cannot use them because they are private...

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

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

complex(double r,double i){real=r;image=i;}

complex complex_add(complex &c2);

complex complex_sub(complex &c2);

complex complex_mult(complex &c2);

complex complex_div(complex &c2);
void display();

private:
	double real;
	double image;
};


complex complex::complex_add(complex &c2)
{
complex c;

c.real=real+c2.real;

c.image=image+c2.image;

return c;
}

complex complex::complex_sub(complex &c2)

{
 complex d;

d.real=real-c2.real;

d.image=image-c2.image;

return d;
}

complex complex::complex_mult(complex &c2)
{
complex f;

f.real=real*c2.real;

f.image=image*c2.image;

return f;
}

complex complex::complex_div(complex &c2)
{
 complex g;
 g.real=real/c2.real;
 g.image=image/c2.image;
 return g;
}


void complex::display()
{
  cout<<"("<<real<<","<<image<<"i)"<<endl;
}


int main()
{
complex c1(2,5),c2(4,9),c3;  //i want input my own complex number.
c3=c1.complex_add(c2);
cout<<"c1=";c1.display();
cout<<"c2=";c2.display();
cout<<"c1+c2=";c3.display();

c3=c1.complex_sub(c2);
cout<<"c1=";c1.display();
cout<<"c2=";c2.display();
cout<<"c1-c2=";c3.display();

c3=c1.complex_mult(c2);
cout<<"c1=";c1.display();
cout<<"c2=";c2.display();
cout<<"c1*c2=";c3.display();

c3=c1.complex_div(c2);
cout<<"c1=";c1.display();
cout<<"c2=";c2.display();
cout<<"c1/c2=";c3.display();

return 0;
}

Take in 2 doubles from the user and then use your constructor to create a new object.

double r,im;
cin >> r >> im;
complex num(r,im);

I am sorry I don't like jonsca's solution, it has ugly temporary variables, that aren't necessary.

The better way to do this (IMHO) is to add two operators. One is operator<< and the other is operator>>

std::istream& operator<<(std::istream& FX,complex& A)
  {  
      A.read(FX);
      return FX;
  }
std::ostream& operator>>(std::ostream& FX,const complex& A)
  {  
      A.write(FX);
      return FX;
  }

Now those two functions allow your to write

complex c;
std::cin>>c;
std::cout<<"You entered "<<c<<std::endl;
}

The only thing you have to write is read/write

void complex::write(std::ostream& FX) const
{
    FX<<r<<"  "<<i;
}  
// AND
void complex::read(std::ostream& FX)
{
   FX>>r>>i;
}

I would add checking etc, to read and allow stuff like 4+i5 etc. I normally don't put the endl within the write function, because it is normal to allow a chained set of functions e.g. std::cout<<"Complex to add are "<<cA<<" + "<<cB<<std::endl;

Another way is to make a get/set functions.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.