defining a class from a template class inside another class
Nov 8, 2020 at 12:54pm UTC
I have a situation similar to the one described below: there is a template class B that is inheriting from a template class A. I want to create a class type_B which is a B<int> and create an instance of this object inside a class C. I found no way to do this so far. Any hint? I am using Dev C++ in Windows 10, but I don't think this is a problem...
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 46 47 48 49 50 51
template <class T> class A{
protected :
T *item;
int t;
public :
A(int s){
item = new T[s];
t=s;
}
void in(const T& elem, int p){
item[p]=elem;
}
print(){
for (int i =0; i< t; i++){
cout<<item[i]<<" " ;
}
cout<<endl;
}
};
template <class Z> class B:public A<Z>{
private :
int position=0;
public :
B(int s):A<Z>(s){
}
void in(const Z& elem){
A<Z>::in(elem, position);
position++;
}
};
class C{
protected :
typedef B<int > B_type;
B_type element(5);
public :
C(){
}
};
Nov 8, 2020 at 10:01pm UTC
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 46 47 48 49 50 51 52 53 54
#include<iostream>
template <class T> class A{
protected :
T *item;
int t;
public :
A(int s){
item = new T[s];
t=s;
}
void in(const T& elem, int p){
item[p]=elem;
}
void print(){
for (int i =0; i< t; i++){
std::cout<<item[i]<<" " ;
}
std::cout<<std::endl;
}
};
template <class Z> class B:public A<Z>{
private :
int position=0;
public :
B(int s):A<Z>(s){
}
void in(const Z& elem){
A<Z>::in(elem, position);
position++;
}
};
class c{
protected :
typedef B<int > b_type;
b_type element{5};
public :
c(){ }
};
int main() {
c c;
}
I'm pretty sure I don't understand what your problem is, but this does compile.
Last edited on Nov 8, 2020 at 10:22pm UTC
Nov 8, 2020 at 10:07pm UTC
Line 17: The return type is missing. Probably void.
Line 42: The round brackets are wrong for initializing. Use curly brackets instead.
Topic archived. No new replies allowed.