簡體   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