I'm trying to mix it up with operator overloading and I can figure out what I'm doing wrong. Here's the code:

#ifndef TEST_H
#define TEST_H

using namespace std;

template <typename T>
class Test
{
private:
	T number;
public:
Test(T);
 friend Test operator+(Test<T> &a, Test<T> &b);
 friend ostream& operator<<(ostream& out, const Test<T> &obj);
};

template <typename T>
Test<int>::Test(T num1)
{
	number = num;
}

template <typename T>
Test<int> operator+(Test<T> &a, Test<T> &b)
{
	return Test(a.number + b.number);
}

template <typename T>
ostream& operator<<(ostream& out, Test<T> &obj)
{
	out<< obj.number;
	return out;
}

#endif

#include <iostream>
#include "Test.h"
using namespace std;
int main()
{
	Test<int> obj1(5);
	Test<int> obj2(2);
	Test<int> obj3(0);

	obj3 = obj1 + obj2;
	cout << obj3;
	return 0;
}

I'm getting an error that says "test.h(21): error C2244: 'Test<T>::{ctor}' : unable to match function definition to an existing declaration"

Recommended Answers

All 3 Replies

If the error is in your test.h file, maybe you should post it. Oh you did. Why do you have the main function in your header file? My mistake, I didn't realize you grouped the header and object file together.

Not sure why you added <int> here?

template <typename T>
Test<int>::Test(T num1)
{
number = num;
}
 
template <typename T>
Test<int> operator+(Test<T> &a, Test<T> &b)
{
return Test(a.number + b.number);
}

I'm no template expert but you can take a look at my code below

#include <iostream>
#include <cstring>

struct mys
{
  double a, b;
};

std::ostream& operator <<(std::ostream & out, const struct mys & s)
{
  return out << s.a << " " << s.b;
}

struct mys operator +(const struct mys & a, const struct mys & b)
{
  struct mys temp;
  memcpy(&temp, &a, sizeof(struct mys));
  temp.a +=  b.a;
  temp.b += b.b;
  return temp;
}

template <typename T>
class my_t
{
  
public:
  
  my_t():the_value() {}
  my_t(T val):the_value(val) {}
  
  my_t operator +(const my_t & a) const
  {
	return this->the_value + a.the_value;
  }
  
  my_t& operator =(const my_t & a)
  {
	if ( this != &a )
	{
	  this->the_value = a.the_value;
	}
	return *this;
  }
  
  T getitsvalue() const { return the_value; }
  
private:
  
  T the_value;
  
};
template <typename T>
std::ostream& operator <<(std::ostream & out, const my_t<T> & m)
{
  return out << m.getitsvalue();
}

int main()
{
  struct mys f = {123.0, 234.0}, g = {34.0, 45.0};
  my_t<struct mys> one(f);
  my_t<struct mys> two(g);
  my_t<struct mys> ans;
  
  ans = one + two;
  
  std::cout << ans << std::endl;
  
  return 0;
}

Note I have a assignment operator=().

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.