Your code has two error:
1) You cannot define friend function body in the class declaration
2) You must declare friend function as template
3) In push function you must increment _index
The following code compile and run right
#include <iosfwd>
template <class T = int, size_t N = 100>
class Stack {
T _data[N];
size_t _index;
public:
Stack() : _index(0) { }
void push(const T& value) {
if ( _index != N)
{
_data[_index] = value;
++_index;
}
else
printf("stack full\n");
}
template <typename TYPE, size_t SIZE>
friend std::ostream& operator<<(std::ostream& os, const Stack<TYPE, SIZE>& stack);
};
template <typename T, size_t N>
std::ostream& operator<<(std::ostream& os, const Stack<T, N>& stack)
{
for (size_t i=0; i < stack._index; ++i)
os << stack._data[i] << " ";
return os;
}
#include <iosfwd>
template <class T = int, size_t N = 100>
class Stack {
T _data[N];
size_t _index;
public:
Stack() : _index(0) { }
void push(const T& value) {
if ( _index != N)
{
_data[_index] = value;
++_index;
}
else
printf("stack full\n");
}
template <typename TYPE, size_t SIZE>
friend std::ostream& operator<<(std::ostream& os, const Stack<TYPE, SIZE>& stack);
};
template <typename T, size_t N>
std::ostream& operator<<(std::ostream& os, const Stack<T, N>& stack)
{
for (size_t i=0; i < stack._index; ++i)
os << stack._data[i] << " ";
return os;
}
To copy to clipboard, switch view to plain text mode
int main()
{
Stack<int, 10> st;
st.push(2);
st.push(5);
st.push(3);
std::cout << st << std::endl;
return 0;
}
int main()
{
Stack<int, 10> st;
st.push(2);
st.push(5);
st.push(3);
std::cout << st << std::endl;
return 0;
}
To copy to clipboard, switch view to plain text mode
Bookmarks