AFAIK, I am supposed to declare a class(and it's functions) in a header file, and then define them in it's respective .cpp file.
Here is my code.
C1.h
#ifndef C1_H_
#define C1_H_
namespace newspace {
class C1 {
public:
void print(); //just a Hello World.
template <typename T1>
T1 power(T1 x, T1 y); // calculate x^y
};
}
#endif
C1.cpp
#include "C1.h"
#include<iostream>
namespace newspace {
void C1::print() // print() defined
{
std::cout<<"Hello World"<<std::endl;
}
template <typename T1>
T1 C1::power(T1 x, T1 y) //calculate x^y // power() defined
{
T1 ans=1;
for (T1 i=0;i<y;i++)
{
ans*=x;
}
return ans;
}
}
main.cpp
#include <iostream>
#include "C1.h"
using namespace std;
int main()
{
newspace::C1 obj1; // created object obj1
obj1.print(); // works perfectly
cout<<"Enter two numbers";
int x,y;
cin>>x>>y;
cout<<obj1.power(x,y); // gives error
return 0;
}
The print() function works properly, but the templated function power() does not work and gives the error
undefined reference to `int newspace::C1::power<int>(int, int)'
What am I doing wrong here? what am I supposed to do?
Aucun commentaire:
Enregistrer un commentaire