user224301
user224301

Reputation: 113

Overloading >> operator

My task is to overload >> and << operators on Stack. They should work like pop and push. So it should look like that

stack << 4.0 << 5.0; // here I pushed two elements
float x, y, z;
stack >> x >> y >> z; //here pop 3 elements to x,y,z

I was told to use array implementation of stack and for << works when I just recalled push.

float pop (){
    if(!empty()){   
    n--;
     return data[n+1];}
    }

void push (float x){
    if (n<MAX){
    data[n++]=x;    
    }else {
    cout<<"Overload!";}
    } 

Stack operator<<(float k){
    push(k);
    }

friend istream & operator>>(istream &in, Stack &ob);    

Now outside of class I tried to define >>, but it's not working.

istream & operator>>(istream  &in, Stack &ob){
}
    in>>ob.pop();
    return in;
}

Could you give me any clue?

Upvotes: 0

Views: 2683

Answers (1)

Richard Hodges
Richard Hodges

Reputation: 69912

Something like this?

#include <iostream>

struct Stack {
    static const int capacity = 10000;

    void push(float x) { data[sp++] = x; }

    float pop() { return data[--sp]; }

    float data[capacity];
    int sp = 0;
};

Stack &operator<<(Stack &s, float x) {
    s.push(x);
    return s;
}

Stack &operator>>(Stack &s, float &x) {
    x = s.pop();
    return s;
}

int main() {
    Stack stack;
    stack << 4.0 << 5.0 << 6.0;
    float x, y, z;
    stack >> x >> y >> z; //here pop 3 elements to x,y,z

    std::cout << x << " " << y << " " << z << std::endl;
}

Upvotes: 2

Related Questions