Complex number program compile-time error at calcu

2019-09-14 05:49发布

问题:

class Complex
{
public:
  Complex(float = 0.0, float = 0.0); //default constructor that uses default arg. in case no init. are in main
  void getComplex(); //get real and imaginary numbers from keyboard
  void sum(Complex, Complex); //method to add two complex numbers together
  void diff(Complex, Complex); //method to find the difference of two complex numbers
  void prod(Complex, Complex); //method to find the product of two complex numbers
  void square(Complex, Complex); //method to change each complex number to its square
  void printComplex(); //print sum, diff, prod, square and "a+bi" form 

private: 
  float real; //float data member for real number (to be entered in by user)
  float imaginary; //float data member for imaginary number (to be entered in by user)
};

Complex::Complex(float r, float i)
{   
  real = r;
  imaginary = i;
}

void Complex::sum(Complex r, Complex i)
{
  sum = r + i; //error here under "sum" and "+"
}

int main()
{
  Complex c;
  c.getComplex();
  c.sum(Complex r, Complex i); //error here under "Complex r"
  c.diff(Complex r, Complex i); //error here under "Complex r"
  c.prod(Complex r, Complex i); //error here under "Complex r"
  c.square(Complex r, Complex i); //error here under "Complex r"
  c.printComplex();

  return 0;
}

I am not allowed to user overloading at all.

I have several errors, but they have a common thread, I believe. They occur at the calculation points in my methods. I don't know how to fix it. I believe I have the public and private parts down, though.

Here are my errors:

Error 7 error C2676: binary '+' : 'Complex' does not define this operator or a conversion to a type acceptable to the predefined operator c:\users\Sarah\desktop\classwork\c++\exam 3 program\exam 3 program\exam 3 program.cpp 37

Error 16 error C3867: 'Complex::sum': function call missing argument list; use '&Complex::sum' to create a pointer to member c:\users\Sarah\desktop\classwork\c++\exam 3 program\exam 3 program\exam 3 program.cpp 58

Error 2 error C2784: 'std::_String_const_iterator<_Elem,_Traits,_Alloc> std::operator +(_String_const_iterator<_Elem,_Traits,_Alloc>::difference_type,std::_String_const_iterator<_Elem,_Traits,_Alloc>)' : could not deduce template argument for 'std::_String_const_iterator<_Elem,_Traits,_Alloc>' from 'Complex' c:\users\Sarah\desktop\classwork\c++\exam 3 program\exam 3 program\exam 3 program.cpp 37

回答1:

void Complex::sum(Complex r, Complex i)
{
    sum = r + i; //error here under "sum" and "+"
}

you are trying to use operator '+' for two Complex instances. It is not defined. variable sum is not defined either. I can guess you wanted to implement c = x + y or c.sum(x,y). Then this function should look like this.real = x.real + y.real; this.img = x.img + y.img

Also you cannot define variables inside function call like this c.sum(Complex r, Complex i);