2017-04-10 71 views
-1

我的任务是在Stack上超载>>和< <运算符。他们应该像流行和推动一样工作。因此,它应该是一个Overloading >> operator

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 

我被告知要使用堆栈的数组实现和< <的作品时,我只是回忆推。

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);  

现在我在类外面试图定义>>,但它不起作用。

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

你能给我任何线索吗?

+1

“>>”运算符应该有一个与'<<'运算符几乎相同的原型。 (看看'stack >> x;'你在哪里找到'istream'?) – molbdnilo

+0

你说你想让'operator >>()'允许像'stack >> some_value'这样的表达式来弹出一个元素。你定义的唯一'operator >>()'是表面上从输入流中读取栈的。你打算如何? – Peter

+0

这是使用运算符重载的可怕方式。即使这样也不能断开原来的意思,使得代码不可读,而且在写入流时也会有效地销毁你的栈(pops元素)。这种副作用是非常危险和可怕的,你真的不想做。 – Ondrej

回答

2

这样的事情?

#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; 
}