-1
#include <iostream>
#include <string.h>
using namespace std;

#define NMAX 10 // pre-processing directive

template<typename T>
class Stack {
public:
T Smain, Saux;
T stackArray[NMAX];
int topLevel;
    int getTopLevel()
    {
      return this->topLevel;
    }
    void push(T x)
     {
    if (topLevel >= NMAX - 1)
        {
                cout<<"The stack is full: we have already NMAX elements!\n";
        return;
            }
            stackArray[++topLevel] = x;
         }
    int isEmpty()
       {
         return (topLevel < 0);
       }
    T pop()
      {
         if (isEmpty()) {
              cout<<"The stack is empty! \n";
         T x;
              return x;
      }
     return stackArray[topLevel--];
       }
    T peek()
   {
   if (isEmpty())
     {
       cout<<"The stack is empty! \n";
       T x;
           return x;
        }
        return stackArray[topLevel];
     }
   void afficher() {
        cout<<"On affiche la pile:";
        for ( int i=0; i<=topLevel; i++ )
           cout<<stackArray[i]<<" ";
        cout<<endl;
    }
    Stack()
    {
       topLevel = -1;
    }
    ~Stack() {
     }
    void change(int i)
    {
        while (Smain.topLevel>i){
            Saux.push(Smain.pop());}
        T aux1=Smain.pop();
        T aux2=Smain.pop();
        Smain.push(aux1);
        Smain.push(aux2);
        while (Saux.topLevel>=0){
           Smain.push(Saux.pop());}
    }
 };
 int main()
 {
     Stack<int> stack1;
     Stack<int> stack2;
      stack1.push(1);
      stack1.push(2);
      stack1.push(3);
      stack1.push(4);
      change(3);
      stack1.afficher();
  return 0;
}

This program has to swap the i and i-1 position of a stack, but i get the error: 'change' was not declared in this scope and i don't know how to make it work. please help me and thanks to you in advance.

  • Slow down. You are asking why a member function call without an object results in a compilation error, yet at the same time you are trying to write a template class. Learn **one feature at a time**, not everything at once. – Christian Hackl Mar 13 '16 at 12:07

2 Answers2

0

change is declared inside the class Stack, so it becomes a method on a Stack instance.

You probably want to call it as stack1.change(3) instead.

xaxxon
  • 19,189
  • 5
  • 50
  • 80
  • i tried but i get more errors if i do that. because the function will not see the elements from the class like Smain and Saux – user3588396 Mar 13 '16 at 11:07
0

You cannot call change() function which is inside a class directly.instead use an class object to call it.

class stack{

}objectname;

int main(){
objectname.change(3);
}
Ajay
  • 125
  • 3
  • 13
  • it gives me a template declaration of 'Stack objectname' error. I really wanna make it work. but your idea sounds very good and i don't know why it doesn't work – user3588396 Mar 13 '16 at 11:59