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
|
template <class T>class BaseExamp { //Base undefined type template object
T i,j; //create type T vars of i, j
public:
void init(T a,T b){ //used in convience constructor
i=a,j=b; //assign a and b
}
BaseExamp(){}
BaseExamp(T a,T b){ init(a, b);} //convience constructor
~BaseExamp(){} //i and j removes from memory
T product() { //definition of individual
return i*j; //get(s) and set(s) for i and j
} //would follow too
};
template <class T>class examp : public BaseExamp<T> { //inherits from Base with type T as well, right?
T* a,b; //In the real world this would be a
public: // reference counting smart pointer of the actual T, right?
void init(T &ii,T &jj){ //these values re-assign by and with ref(s)
&a=ii,&b=jj; //right?
}
examp(){} //std ctr
examp(T &ii,T &jj){ init(ii, jj);} //conv. ctr
~examp(){}
T product() { //ensure properness with
return ((&a)*&b); //these exact parentheses
} //right?
};
int main() {
examp <long double>*ptr; //create a pointer of type examp
long double i; //just a tmp loop var
ptr = new examp<long double>[6]; //6 pointers = 6 objects allocatted
if(!ptr) { //IMPORTANT: Always do this check for all poniters
printf("Allocation error.\n"); // (inside it's wrapped smart pointer, not shown here)
return 1; // before terminattion, or the try something else function...
}
for(i=0;i<6;i++) { //assigns i and j for all ptr[i](s)
int xx;
xx = i;
ptr[i].init(xx,xx); //[0]=0,0; [1]=1,1;...[4]=4,4; [5]=5,5;
}
for(i=0;i<6;i++) {
printf("Product[%i]is:%f\n", i, ptr[i].product());//std printf call
}
delete[] ptr; //proper deletion of ptr with no smart pointer
return 0; //right?
}
|