繁体   English   中英

无法使用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 Point{
...
public:
    friend std::ostream& operator<< (std::ostream& stream, const Point& p) 
        {cout<<p.getx<<p.gety<<endl;}
...
};

另外,您忘记在while语句中从堆栈中pop元素,这将导致无限循环。

cout<<top; 

不起作用,因为point是由您创建的类,编译器无法打印它。 您应该自己打印点的单个元素。 喜欢

     cout<<point.getx<<point.gety<<endl;

或者在您的类中为运算符<<创建一个重载函数,该函数执行上述类似的操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM