Operator >> Error
Sep 6, 2012 at 5:22pm UTC
Hi I am having a problem with separating my overloaded operator into the .cpp of my class.
main.cpp
1 2 3 4 5 6 7 8 9
#include <iostream>
#include "test.h"
using namespace std;
int main()
{
test<double > testObject;
cin >> testObject
return 0;
}
test.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#ifndef TEST_H
#define TEST_H
#include <iostream>
using namespace std;
template <class T>
class test
{
friend istream &operator >>(istream &Input, test<T> &x);
//If i put the code here it works fine
public :
private :
T ** testArr;
test.cpp
1 2 3 4 5 6 7 8
#include <iostream>
#include "test.h"
using namespace std;
template <class T>
istream &operator >>(istream &userIn, matrix<T> &obj){
}
The Error that I get is
undefined reference to `operator>>(std::istream&, matrix<double>&)'|
Sep 6, 2012 at 5:49pm UTC
You declared the friend function as a non-template function inside class test however in the cpp file you are declaring it as a template function.
I think that the declaration should look the following way
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#ifndef TEST_H
#define TEST_H
#include <iostream>
using namespace std;
template <class T>
class test
{
template <typename U>
friend istream & operator >>(istream &, test<U> & );
//If i put the code here it works fine
public :
private :
T ** testArr;
....
template <class T>
istream & operator >>( istream &userIn, matrix<T> &obj )
{
return ( userIn );
}
Also do not forget to place all definitions of the template class in this header.
Last edited on Sep 6, 2012 at 5:52pm UTC
Sep 6, 2012 at 6:27pm UTC
Okay I understand but is it possible to place all the definition inside the test.cpp instead of the header?
Sep 6, 2012 at 6:31pm UTC
The main shall see the definitions that to generate an instantiation of a template.
Sep 6, 2012 at 7:45pm UTC
In english: You need to have template definitions in headers.
Sep 6, 2012 at 7:56pm UTC
@Stewbond Thank you lol
Topic archived. No new replies allowed.