J
jianqi.wang
Hi, everyone, I started learning C++ two weeks ago. I am trying to
play with template with constant expressions for template. So I wrote
a very simple program as follows... There are three files: gfield.h,
gfield.cpp and main.c.
//////////////////////////////////////
// gfield.h
#pragma once
#include <iostream>
using namespace std;
template <int n>
class gfield
{
public:
explicit gfield(int x):_num(x%n){}
~gfield(void);
int get_value(void) const {return _num;}
private:
int _num;
};
template <int n>
ostream& operator <<(ostream& os,const gfield<n>& gf);
///////////////////////////
//gfield.cpp
#include "gfield.h"
#include <iostream>
using namespace std;
template <int n>
gfield<n>::~gfield(void)
{
}
template <int n>
ostream& operator <<(ostream& os,const gfield<n>& gf)
{
os<<gf.get_value()<<endl;
return os;
}
///////////////////////
// main.cpp
#include <cstdlib>
#include <string>
#include <cstdio>
#include <iostream>
#include "gfield.h"
using namespace std;
main()
{
gfield<2> gf(3);
cout<<gf;
cout<<test_return();
}
The problem I met is that there will be link error : unresolved
external symbol... Basically, the compiler could not find operator <<
and gfield<n>::~gfield(void). However, if I move the definition of
these two function definitions to either main.cpp or gfield.h, it
would work.
Can anyone help me on this? Thank you very much!
play with template with constant expressions for template. So I wrote
a very simple program as follows... There are three files: gfield.h,
gfield.cpp and main.c.
//////////////////////////////////////
// gfield.h
#pragma once
#include <iostream>
using namespace std;
template <int n>
class gfield
{
public:
explicit gfield(int x):_num(x%n){}
~gfield(void);
int get_value(void) const {return _num;}
private:
int _num;
};
template <int n>
ostream& operator <<(ostream& os,const gfield<n>& gf);
///////////////////////////
//gfield.cpp
#include "gfield.h"
#include <iostream>
using namespace std;
template <int n>
gfield<n>::~gfield(void)
{
}
template <int n>
ostream& operator <<(ostream& os,const gfield<n>& gf)
{
os<<gf.get_value()<<endl;
return os;
}
///////////////////////
// main.cpp
#include <cstdlib>
#include <string>
#include <cstdio>
#include <iostream>
#include "gfield.h"
using namespace std;
main()
{
gfield<2> gf(3);
cout<<gf;
cout<<test_return();
}
The problem I met is that there will be link error : unresolved
external symbol... Basically, the compiler could not find operator <<
and gfield<n>::~gfield(void). However, if I move the definition of
these two function definitions to either main.cpp or gfield.h, it
would work.
Can anyone help me on this? Thank you very much!