I posted this yesterday. People suggested that I should have Point.h and Point.cpp files since I’m using template. I created separate files for my class Point, and I’m still receiving errors.
//Point.h
Point(T = 0, T = 0, string = "Deafault Point");
~Point();
T operator-(const Point<T> &);
//Point.cpp
template < typename T >
Point<T>::Point(T x,T y, string name)
:X(x), Y(y), Name(name)
{
}
template < typename T >
Point<T>::~Point()
{
}
template < typename T>
T Point<T>::operator-(const Point<T> &rhs)
{
cout << "\nThe distance between " << getName() << " and "
<< rhs.getName() << " = ";
return sqrt(pow(rhs.getX() - getX(), 2) + pow(rhs.getY() - getY(), 2));;
}
//main.cpp
#include <iostream>
#include <math.h>
#include "Point.h"
using namespace std;
int main () {
Point<double> P1(3.0, 4.1, "Point 1");
cout << P1;
Point<double> P2(6.4, 2.9, "Point 2");
cout << P2;
cout << (P2 - P1);
return EXIT_SUCCESS;
}
This is what I got:
Undefined symbols:
"std::basic_ostream<char, std::char_traits<char> >& operator<< <double (std::basic_ostream<char, std::char_traits<char> >&, Point<double> const&)", referenced from:
_main in main.o
_main in main.o
"Point<double>::operator-(Point<double> const&)", referenced from:
_main in main.o
"Point<double>::Point(double, double, std::basic_string<char, std::char_traits<char>, std::allocator<char> >)", referenced from:
_main in main.o
_main in main.o
"Point<double>::~Point()", referenced from:
_main in main.o
_main in main.o
_main in main.o
_main in main.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
Any help is appreciated…
Whoever suggested this is dead wrong. Implementations for templates must be visible.
You can separate the implementation to a file, but you need to include it as well afterwards. The only situation when you can hide the implementation of a template is when you know the specializations and declare them beforehand. (this doesn’t apply here)
You need a single file for the template:
Also, the naked
stringin the header suggests you have ausing namespace std;in the header as well. That’s bad practice, remove theusingdirective and qualify the namestd::string.