0

Hi can anyone help? I need to print the top element of a stack of Objects (in this case points) and i am unable to find a solution online. I have attempted changing the datatype of top or straight up calling pointStack.top() in the cout but i have had no luck. Note. I have not included the Pop function as error C2679 is the issue

#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;
}
Rowan Berry
  • 113
  • 7

2 Answers2

2

According to your description, I think you forget to overload the << operator, you should add a operator overload function for you Point class, check here.

For example:

class Point{
...
public:
    friend std::ostream& operator<< (std::ostream& stream, const Point& p) 
        {cout<<p.getx<<p.gety<<endl;}
...
};

Plus, you forget to pop the element from the stack in your while statement, this will lead to infinite loop.

Community
  • 1
  • 1
Jiahao Cai
  • 1,204
  • 1
  • 11
  • 25
0
cout<<top; 

doesn't work because point is a class created by you, the compiler cant print it. You should print the individual element of point by yourself. Like

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

Or create an overload function for operator << in your class which does similar thing mentioned above.

Chandini
  • 530
  • 2
  • 11