C++ 超载>&燃气轮机;操作人员
我的任务是过载>>和类似的东西C++ 超载>&燃气轮机;操作人员,c++,stack,operator-overloading,C++,Stack,Operator Overloading,我的任务是过载>>和类似的东西 #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<
#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;
}
#包括
结构堆栈{
静态常数int容量=10000;
void push(float x){data[sp++]=x;}
float pop(){返回数据[--sp];}
浮动数据[容量];
int sp=0;
};
堆栈和运算符(堆栈和s、浮点和x){
x=s.pop();
返回s;
}
int main(){
堆叠;
stack>y>>z;//这里将3个元素弹出到x、y、z
std::难道>
操作符应该有一个与
操作符几乎相同的原型(看看codestack>x;
你在哪里找到istream
?)你说你想操作符>>()
允许像堆栈>>这样的表达式弹出一个元素。唯一的操作符>>()
您定义的是一种表面上从输入流读取堆栈的方法。您打算使用哪种方法?这是使用运算符重载的可怕方式。即使这样也不会中断原始含义,使代码无法读取,但也会有效地破坏堆栈(pops元素)当您将其写入流时。这种副作用是危险的,而且可能是您确实不想做的事情。当您流>>var时,var必须是左值,ob.pop()不是左值;好的。不知道为什么我使用istream。现在尝试了不同的方法:float-friend操作符>>(堆栈s,float&k){k=s.pop();返回k;}
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;
}
#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;
}