Overloading the add statement inside the template class

I am trying to write code to easily handle complex numbers. I use the template class, and I have problems with operator overloading (in particular, +, -, *, /). I am trying to declare overloads inside my template class, and then define them in the same header file.

My header code is as follows:

#ifndef MY_CLASS_H
#define MY_CLASS_H

template <class T> class complex
{

private:
    T re,im;
public:
    // Constructors & destructor
    complex(){re=im=0;}
    complex(T r, T i){re=r; im=i;}
    ~complex(){}

    // Return real component
    T realcomp() const {return re;}
    // Return imaginary component
    T imagcomp() const {return im;}


    // Overload + operator for addition 
    complex<T> operator+(const complex<T> &C);

....

};
#endif


#include<iostream>
#include<cmath>
using namespace std;

template <class T> complex<T>& complex<T>::operator+(const complex &C){
complex<T> A(re+C.realcomp(),im+C.imagcomp());
return A;
}

This returns errors that I still could not solve, and I'm not quite sure where I made a mistake. The combination of me, being a C ++ newbie and trying to combine solutions to other problems on this website, probably meant that my code is a bit of a mess - I'm sorry!

Any help would be greatly appreciated.

+3
source share
4 answers

complex<T>::operator+ complex<T>, complex<T>&. , .

, , , operator+ .

-.

template <class T> class complex
{
private:
    T re,im;
public:
    // Constructors & destructor
    complex() : re(), im() {}
    complex( const T& r, const T& i ) : re(r), im(i) {}
    ~complex(){}

    // Return real component
    T realcomp() const {return re;}
    // Return imaginary component
    T imagcomp() const {return im;}


    // Overload + operator for addition 
    complex<T> operator+(const complex<T> &C)
    {
       return complex<T>( re + C.realcomp(), im + C.imagcomp() );
    }
};
+2

. :

template <class T> complex<T>& complex<T>::operator+(const complex &C){

template <class T> complex<T> complex<T>::operator+(const complex &C){

( "&" )

0

:

template <class T> complex<T> complex<T>::operator+(const complex<T> &C){ 
  complex<T> A(re+C.realcomp(),im+C.imagcomp()); 
  return A; 
} 

The return value is declared by the object in the class, and patameter does not have a template parameter

0
source

you return a local variable as a reference. plus declaration is different:

you declare that you are returning the complex during the definition, you are returning complex &

0
source

All Articles