Click here to Skip to main content
15,742,477 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Can anyone help me to write a code for "template operator overloading without class for complex number addition and multiplication"the main theme is i should not use "class" and i can use structure and i should use "template" to add and multiply for two complex number, i tried to search in internet but i did not found one. is my code:
template <typename complex_t> // template inz.
// struct
struct complex
      complex Max(complex_t real_v, complex_t imag_v) 
// i'm not sure what i have to declare inside this function 
      return 0;
      complex()//default value
      int real=0;
      int imag=0;       
complex operator + complex (Max(a,b))
  complex c;
complex operator ++ max(complex& c3)  // postfix increment
  c3.real = c3.real + 1;
  c3.imag = c3.imag + 1;
  return c3;
void main()  
complex c1(1,-2),c2(2.3,19),c3;

What I have tried:

i have tried to search in internet but i did not get any clear answer and even i tried to write code but it's not working.
Updated 15-Sep-16 22:02pm

1 solution

Why do you need templates for such a task?
Could you please show us your 'not working code'?
Here an example of global (without class) operator overloading: How to overload opAssign operator globally in C++ - Stack Overflow[^].

I give you an example

#include <iostream>
using namespace std;

template <typename complex_t>
struct complex
  complex_t real, imag;
  complex( complex_t r, complex_t i):real(r), imag(i){}
  complex():real(complex_t()), imag(complex_t()){}

template <typename complex_t >
complex<complex_t> operator + ( const complex<complex_t> & a, const complex<complex_t> & b)
  complex<complex_t> c;
  c.real = a.real + b.real;
  c.imag = a.imag + b.imag;

int main()
  complex <double> c1(1,-2);
  complex <double> c2(2.3,19);
  complex <double> c3 = c1 + c2;

  cout << "c3.real = " << c3.real << ", c3.imag = " << c3.imag << endl;

Note, since C++11, you might write
template <typename complex_t>
struct complex
  complex_t real{}, imag{};
  complex( complex_t r, complex_t i):real(r), imag(i){}


Share this answer
Arul Prasath Kolandasamy 16-Sep-16 3:48am    
1. Thank for your reply sir, because this is my task to complete. is my code: given above
CPallini 16-Sep-16 4:38am    
See my updated solution.
Arul Prasath Kolandasamy 16-Sep-16 7:12am    
Thank you it's working.
CPallini 16-Sep-16 7:55am    
Did you really doubt about? :-)
You are welcome.

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

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900