无法使用 OOP C++ 打印堆栈项
Unable to print stack items using OOP C++
嗨,有人可以帮忙吗?我需要打印一堆对象的顶部元素(在本例中为点),但我无法在线找到解决方案。我曾尝试更改 top 的数据类型或直接在 cout 中调用 pointStack.top() 但我没有运气。笔记。我没有包含 Pop 函数,因为错误 C2679 是问题
#include <iostream>
#include <stack>
#include "point.h"
using namespace std;
int main(){
stack<Point> pointStack;
Point p;
int i;
int counter = 0;
for (i = 0; i < 10; i++){
p.pCreate();
Point p1(p.getXPos(), p.getYPos());
pointStack.push(p1);
counter++;
}
while (!pointStack.empty()){
Point top = pointStack.top();
cout << top; // error C2679
cout << pointStack.top(); // also error C2679
}
system("PAUSE");
return 0;
}
#ifndef __Point__
#define __Point__
using namespace std;
class Point{
private:
int x, y;
public:
Point();
Point(int x, int y);
int getYPos(){ return y; }
int getXPos(){ return x; }
void pCreate();
};
#endif
Point::Point(){
x = 0, y = 0;
}
Point::Point(int a, int b){
x = a;
y = b;
}
void Point::pCreate(){
x = -50 + rand() % 100;
y = -50 + rand() % 100;
}
根据你的描述,我认为你忘记重载<<操作符,你应该为你添加一个操作符重载函数Point
class,检查here。
例如:
class Point{
...
public:
friend std::ostream& operator<< (std::ostream& stream, const Point& p)
{cout<<p.getx<<p.gety<<endl;}
...
};
此外,您在 while
语句中忘记 pop
堆栈中的元素,这将导致无限循环。
cout<<top;
不起作用,因为点是由您创建的 class,编译器无法打印它。
您应该自己打印点的单个元素。
喜欢
cout<<point.getx<<point.gety<<endl;
或者在你的 class 中为 operator << 创建一个重载函数,它做与上面提到的类似的事情。
嗨,有人可以帮忙吗?我需要打印一堆对象的顶部元素(在本例中为点),但我无法在线找到解决方案。我曾尝试更改 top 的数据类型或直接在 cout 中调用 pointStack.top() 但我没有运气。笔记。我没有包含 Pop 函数,因为错误 C2679 是问题
#include <iostream>
#include <stack>
#include "point.h"
using namespace std;
int main(){
stack<Point> pointStack;
Point p;
int i;
int counter = 0;
for (i = 0; i < 10; i++){
p.pCreate();
Point p1(p.getXPos(), p.getYPos());
pointStack.push(p1);
counter++;
}
while (!pointStack.empty()){
Point top = pointStack.top();
cout << top; // error C2679
cout << pointStack.top(); // also error C2679
}
system("PAUSE");
return 0;
}
#ifndef __Point__
#define __Point__
using namespace std;
class Point{
private:
int x, y;
public:
Point();
Point(int x, int y);
int getYPos(){ return y; }
int getXPos(){ return x; }
void pCreate();
};
#endif
Point::Point(){
x = 0, y = 0;
}
Point::Point(int a, int b){
x = a;
y = b;
}
void Point::pCreate(){
x = -50 + rand() % 100;
y = -50 + rand() % 100;
}
根据你的描述,我认为你忘记重载<<操作符,你应该为你添加一个操作符重载函数Point
class,检查here。
例如:
class Point{
...
public:
friend std::ostream& operator<< (std::ostream& stream, const Point& p)
{cout<<p.getx<<p.gety<<endl;}
...
};
此外,您在 while
语句中忘记 pop
堆栈中的元素,这将导致无限循环。
cout<<top;
不起作用,因为点是由您创建的 class,编译器无法打印它。 您应该自己打印点的单个元素。 喜欢
cout<<point.getx<<point.gety<<endl;
或者在你的 class 中为 operator << 创建一个重载函数,它做与上面提到的类似的事情。