-1

I get the following errors :

public: void __thiscall Number<int>::displayNumber(void)"
(?displayNumber@?$Number@N@@QAEXXZ) referenced in function _main

public: __thiscall Number<int>::Number<int>(int)" 
(??0?$Number@N@@QAE@N@Z) referenced in function _main

when I have my code as follows

Filename................ Number.h

#ifndef NUMBER_H
#define NUMBER_H
#include<iostream>
#include<string>

using namespace std;

template <class T>

class Number
{
  private:
      T number;
  public:
      Number(T num);
      void displayNumber(void);

};


#endif

Filename ................... Number.cpp

#include<iostream>
#include<string>
#include"Number.h"
using namespace std;

template <class T>
Number<T>::Number(T num)
  {
   number = num;
  }

template <class T>
void Number<T>::displayNumber(void)
  {
   cout<<" Number is "<<number<<endl;
  }

Filename ........... main.cpp

#include<iostream>
#include<string>
#include"Number.h"
using namespace std;


int main()
 {
  Number<int> n(10);
  n.displayNumber();
 }

But when I cut my main code and paste it in the Number.cpp file, it works perfectly.

Amardeep reddy
  • 127
  • 2
  • 10

1 Answers1

0

You must move your template function definitions to the header file. For why, see here: Why can templates only be implemented in the header file?

If you don't like that, simply rename Number.cpp to Number.inl or something and #include it at the bottom of Number.h. This has the effect of moving the contents of the file to the header, but still lets you keep two separate files for organizational purposes.

Community
  • 1
  • 1
John Zwinck
  • 239,568
  • 38
  • 324
  • 436