2017-04-04 114 views
0

嗨,任何人都可以帮忙吗?我需要打印对象堆栈的顶部元素(在本例中为点),我无法在线找到解决方案。我试图改变顶部或直线的数据类型在cout中调用pointStack.top(),但我没有运气。注意。我没有将弹出功能错误C2679是问题无法使用OOP打印堆栈项目C++

#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; 
} 
+1

如果您提供[MCVE](https://stackoverflow.com/help/mcve),那就太好了。你没有显示“point.h”。 – javaLover

+0

[error C2679:binary'<<':no operator found](http://stackoverflow.com/questions/22724064/error-c2679-binary-no-operator-found-which-takes-a-right-hand- operand-of)可能有帮助 – javaLover

+0

确定它是非常基本的,但会做 –

回答

2

根据你的描述,我想你忘记重载< <运营商,你应该添加一个运算符重载函数为你Point类,检查here

例如:

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

另外,你忘了pop从堆栈的元素在你的while声明,这将导致无限循环。

+0

谢谢你,我现在认为在网络上的MS的例子,我知道我一直在寻找,加入 “朋友的ostream&运算符<<(ostream的和流,const的点& p);” “的ostream&运算符<<(ostream的和OS,常量点&p) { \t OS << PX << “” << PY; \t回报OS; }” 要获得巨大成功 –

+0

@RowanBerry我的荣幸代码:) – Jiahao

0
cout<<top; 

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

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

或创建操作< <在你的类,它没有类似的事情上面提到过载功能。