问题描述
刚开始用 C++ 编程.
Just started programming in C++.
我已经创建了一个 Point 类、一个 std::list 和一个迭代器,如下所示:
I've created a Point class, a std::list and an iterator like so:
class Point {
public:
int x, y;
Point(int x1, int y1)
{
x = x1;
y = y1;
}
};
std::list <Point> pointList;
std::list <Point>::iterator iter;
然后我将新点推送到 pointList 上.
I then push new points onto pointList.
现在,我需要遍历 pointList 中的所有点,因此我需要使用迭代器进行循环.这就是我搞砸的地方.
Now, I'm needing to iterate through all the points in pointList, so I need to loop using the iterator. This is where I get screwed up.
for(iter = pointList.begin(); iter != pointList.end(); iter++)
{
Point currentPoint = *iter;
glVertex2i(currentPoint.x, currentPoint.y);
}
你们是对的,问题不在于我迭代列表.问题似乎出在我试图将某些内容推送到列表时.
You guys were right, the problem isn't in my iterating the list. It appears the problem is when I am attempting to push something on to the list.
确切的错误:
mouse.cpp: 在函数 void mouseHandler(int, int, int, int)' 中:mouse.cpp:59: 错误:请求从
Point*' 转换为非标量类型`Point'
mouse.cpp: In function
void mouseHandler(int, int, int, int)': mouse.cpp:59: error: conversion from
Point*' to non-scalar type `Point' requested
那些行是:
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
Point currentPoint = new Point(x, y);
pointList.push_front(currentPoint);
}
Point* 和非标量类型 Point 之间的转换是什么?我只是想创建新的点并将它们推到这里的列表中.
What does it conversion between Point* to non-scalar type Point? I'm just trying to create new points and push them onto the list here.
推荐答案
那应该是一段有效的代码.
That should be a valid bit of code.
#include <iostream>
#include <list>
class Point {
public:
int x, y;
Point(int x1, int y1)
{
x = x1;
y = y1;
}
};
int main()
{
std::list<Point> points;
points.push_back(Point(0, 0));
points.push_back(Point(1, 1));
points.push_back(Point(2, 2));
std::list<Point>::iterator iter;
for(iter = points.begin(); iter != points.end(); ++iter)
{
Point test = *iter;
std::cout << test.x << ", " << test.y << "; ";
}
std::cout << std::endl;
return 0;
}
使用此代码:
jasons-macbook41:~ g++ test.cpp
jasons-macbook41:~ ./a.out
0, 0; 1, 1; 2, 2;
jasons-macbook41:~
尽管我不会像您的代码那样创建 Point 的临时副本.我会像这样重写循环:
Although I wouldn't create a temporary copy of the Point as your code does. I'd rewrite the loop like this:
for(iter = points.begin(); iter != points.end(); ++iter)
{
std::cout << iter->x << ", " << iter->y << "; ";
}
迭代器在语法上类似于指针.
An iterator is syntactically similar to a pointer.
鉴于您的新问题,请从构造线上删除新".那是创建一个指向 Point 的指针,而不是堆栈上的 Point.这将是有效的:
Given your new problem, drop the "new" from the construction line. That's creating a pointer to a Point, as opposed to a Point on the stack. This would be valid:
Point* temp = new Point(0, 0);
或者这个:
Point temp = Point(0, 0);
你最好选择后者.
这篇关于为什么我不能把这个对象推到我的 std::list 上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!