How to use the template class in another class?

I have this template class and I want to use it in another class but I have trouble with FloatStack fs(5) ; how should I fix it?


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
#ifndef STACK_H
#define STACK_H
//stack.h
#pragma once
template <class T>
class Stack
{
public:
    Stack(int = 10) ;
    ~Stack() { delete [] stackPtr ; }
    int push(const T&);
    int pop(T&) ;  // pop an element off the stack
    int isEmpty()const { return top == -1 ; }
    int isFull() const { return top == size - 1 ; }
private:
    int size ;  // Number of elements on Stack
    int top ;
    T* stackPtr ;
} ;

//constructor with the default size 10
template <class T>
Stack<T>::Stack(int s)
{
    size = s > 0 && s < 1000 ? s : 10 ;
    top = -1 ;  // initialize stack
    stackPtr = new T[size] ;
}
 // push an element onto the Stack
template <class T>
int Stack<T>::push(const T& item)
{
    if (!isFull())
    {
        stackPtr[++top] = item ;
        return 1 ;  // push successful
    }
    return 0 ;  // push unsuccessful
}

// pop an element off the Stack
template <class T>
int Stack<T>::pop(T& popValue)
{
    if (!isEmpty())
    {
        popValue = stackPtr[top--] ;
        return 1 ;  // pop successful
    }
    return 0 ;  // pop unsuccessful
}
#endif // STACK_H  




1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ifndef TEST_H
#define TEST_H
#include "Stack.h"

class test
{
public:
    test();
    typedef Stack<float> FloatStack ;

    FloatStack fs(5) ;
};

#endif // TEST_H  

Last edited on
Either use curly brackets when specifying the default initializer for fs

 
FloatStack fs{5};

or use the member initializer list when defining the constructor.

1
2
3
4
test::test()
:	fs(5)
{
}
Last edited on
The a default-member-initializer must be a brace-or-equals-initializer

1
2
3
4
5
6
7
8
9
10
class test
{
public:
    test();
    typedef Stack<float> FloatStack ;

    // FloatStack fs(5) ; // *** no
    FloatStack fs{5} ; // use {}
    // or: FloatStack fs = FloatStack(5) ; // or use =
};
Topic archived. No new replies allowed.