Kelvin@!!! wrote:
template<class T> class Index
{
public:
T idx;
Index(T i)
{
idx = i;
};
};
int main()
{
Index<double> f( 1.3 );
}
thnx guys...
but here comes another problem when im trying to wirte a sub class
--- code for iPerf -------
class iPerf : public Index<double>
{
public:
iPerf( double i )
{
idx = i;
}
};
----- compiling err msg ------
'Index<T>': no appropriate default constructor with [ T = double ]
You can do A, B, or both.
A) Define a default constructor for Index<>.
--or--
B) change iPerf<> so that it explicitly calls Index<>'s conversion
constructor.
If there is a meaningful default value for idx, then I'd go with A&B.
Otherwise I'd go with B. Whichever way is right, it's very likely that
you also want to define a class copy constructor for Index<>. There are
some other potentially troublesome things too. Here's the way I'd write
it IFF there is a meaningful default value for idx. (I switched your
type from double to long):
#include <iostream>
using namespace std;
template < typename T > class Index
{
public:
T idx;
Index() :idx() {}
Index(const Index & that) :idx(that.idx) {}
explicit Index(T that) :idx(that) {}
virtual ~Index(){}
};
class iPerf : public Index< long >
{
public:
iPerf() {}
iPerf(const iPerf & that) :Index< long >(that) {}
explicit iPerf(long that) :Index< long >(that) {}
};
int main()
{
iPerf a(3);
cout << a.idx << endl;
}
You might benefit from looking into the following topics. I put them in
what I think is their order of importance. I think you're in for a lot
of heartache until you master the first two: mastering the rest of them
will just make your programming life easier and easier.
special member functions
slicing
virtual destructor
member initializer list
conversion constructor
automatic conversion
explicit constructor
explicit initialization of fundamental types