Hey, I am trying to learn how templates work(and how can I make use of them).
I want to make class Coordinates, that allows me to create coordinates of various types(so coordinates x and y can be int, double, or even of my own type, let's say, fraction).
However, I have problem with creating functions and making them work. Here's code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
//main.cpp
#include <iostream>
#include "Coordinates.h"
int main()
{
Coordinates<int> coor(3,12);
coor.print();
return 0;
}
//end of main.cpp
//Coordinates.h
#ifndef COORDINATES_H
#define COORDINATES_H
#include <iostream>
template <class T> class Coordinates{
public:
Coordinates() {};
Coordinates(T ax, T ay) {x = ax; y = ay;}
~Coordinates() {};
T getX() { return x; }
void setX(T val) { x = val; }
T getY() { return y; }
void setY(T val) { y = val; }
void print();
protected:
private:
T x;
T y;
};
#endif // COORDINATES_H
//end of coordinates.h
//coordinates.cpp
#include "Coordinates.h"
template <class T>
void Coordinates<T>::print() {
std::cout<<"x: "<<x<<"\ny: "<<y<<std::endl;
}
//end of coordinates.cpp
|
What compiler said:
main.cpp|7|undefined reference to `Coordinates<int>::print()'
I'm not sure if I understand the problem, and I definitely don't know how to fix it.
Also, I'd like to ask a bonus question, so I don't spam forum with other threads: when exactly should I create destructors? Only if my class have pointer? Or only if memory for this pointer is dynamically allocated?