我有一个问题,我无法打印出在列表‘顶点’内保存的一组和弦。为了解释,“顶点”是一个类,它基本上包含两个坐标,构成一个顶点(其中两条形状的直线相交)。该问题在第二个for循环中,该循环用于打印列表中的坐标。有人能帮我把这个印出来吗?到目前为止,我尝试过无数的方法和错误,一直给我一个问题。代码在下面,谢谢您的帮助!
INT主
int main(){
//obj
Console con;
RandomNumber rand;
Vertex vertex;
//Declarations
list<Vertex>vertices;
//list<Vertex>::iterator ii;
//set Vertex coords and push into list
for (int i = 0; i <= 8; i++){
vertices.push_back(Vertex(rand.random(0, 10), rand.random(0, 10)));
}
//iterate through the list outputting a char at each vertex (coords)
for (list<Vertex>::iterator ii = vertices.begin(); ii != vertices.end(); ii++){
cout << vertices[ii];
}
system("pause");}
顶点类
#pragma once
class Vertex
{
int x;
int y;
public:
Vertex(int x = 10, int y = 10);
~Vertex();
int getX() const;
int getY() const;
void setX(unsigned x);
void setY(unsigned y);
bool operator== (const Vertex &p2) const;
};
#include "Vertex.h"
Vertex::Vertex(int x, int y)
{
this->x = x;
this->y = y;
}
Vertex::~Vertex(){}
int Vertex::getX() const {
return x;
}
int Vertex::getY() const {
return y;
}
void Vertex::setX(unsigned x) {
this->x = x;
}
void Vertex::setY(unsigned y) {
this->y = y;
}
bool Vertex::operator== (const Vertex &point) const {
return (this->x == point.getX()) && (this->y == point.getY());
}发布于 2015-03-19 13:58:37
//iterate through the list outputting a char at each vertex (coords)
for (list<Vertex>::iterator ii = vertices.begin(); ii != vertices.end(); ii++){
cout << vertices[ii];
}这在本质上是错误的。您需要使用迭代器,就像它是指向列表中的第二级对象的指针一样。
for (list<Vertex>::iterator ii = vertices.begin(); ii != vertices.end(); ii++){
cout << ii->getX() << ',' << ii->getY();
// if you have an overload for 'operator <<(std::ostream&, Vertex)' you can also do
cout << *ii
}发布于 2015-03-19 14:01:34
<<运算符不适用于自定义类型。当遇到<<类时,您需要指定Vertex操作符的行为方式。
您需要生成一个理解顶点类的签名。承担以下职能:
std::ostream& operator<<(std::ostream &os, const Vertex &vertex) {
os << "Node: [" << vertex.getX() << ", " << vertex.getY() << "]";
return os;
}这将允许您使用您编写的代码。
发布于 2015-03-19 14:06:44
您需要向类添加一个函数:
声明:
friend std::ostream& operator <<(std::ostream &os,const Vertex &obj);和执行情况:
std::ostream& operator<<( std::ostream &os,const Vertex &obj )
{
os << << obj.getX() << ',' << obj.getY();
return os;
}这将声明<<操作符重载,如here.所示。
您还必须将迭代更改为:
for (list<Vertex>::iterator ii = vertices.begin(); ii != vertices.end(); ii++){
cout << *ii;
}https://stackoverflow.com/questions/29146397
复制相似问题