[英]How do i get pointers value? C++
So I want to get the value from an item of vector.所以我想从向量项中获取值。 The vector contains Line items.
该向量包含行项目。 Line has to pointers Vertex *p1 and Vertex *p2.
Line 必须指向 Vertex *p1 和 Vertex *p2 指针。 and Vertex has fields of x and y.
和顶点具有 x 和 y 的字段。 How can i make my code give me the values of those x and y?
我怎样才能让我的代码给我那些 x 和 y 的值?
for(Line<Vertex> line : lines){
painter.drawLine(line.p1->x + 5, line.p1->y + 5, line.p2->x + 5, line.p2->y + 5);
}
Line class is as following:线类如下:
template<class T>
class Line {
public:
T *p1;
T *p2;
Line (T *v1, T *v2)
: p1(v1),
p2(v2)
{}
Line (const Line& l){
if(this != &l){
p1 = l.p1;
p2 = l.p2;
}
}
Line& operator= (const Line& l) {
if (this == &l)
return *this;
p1 = l.p1;
p2 = l.p2;
return *this;
}
~Line (){
}
};
Vertex class:顶点类:
class Vertex {
public:
float x = 0;
float y = 0;
Vertex() = default;
Vertex(float nx, float ny);
float distanceFrom(Vertex v);
};
Main:主要的:
std::vector<Line<Vertex>> lines;
Vertex *firstPoint;
Vertex *secondPoint;
bool firstPointChosen = false;
bool secondPointChosen = false;
if(!firstPointChosen){
for(Vertex vertex : vertices){
firstPoint = &vertex;
firstPointChosen = true;
break;
}
}
else{
for(Vertex vertex : vertices){
secondPoint = &vertex;
secondPointChosen = true;
break;
}
}
if(firstPointChosen && secondPointChosen){
Line<Vertex> line(firstPoint, secondPoint);
lines.push_back(line);
update();
firstPointChosen = false;
secondPointChosen = false;
}
for(Line<Vertex> line : lines){
painter.drawLine(line.p1->x + 5, line.p1->y + 5, line.p2->x + 5, line.p2->y + 5);
}
How do i get make the first block of code return the values of x and y for each line that i have added to the lines vector?我如何让第一个代码块为我添加到行向量的每一行返回 x 和 y 的值?
Currently it doesn't return anything or i'm missunderstanding something.目前它没有返回任何东西,或者我误解了一些东西。
EDIT: The main class is alot bigger, but it is called in that order.编辑:主类要大得多,但按此顺序调用。 First it chooses the first vertex, then second.
首先它选择第一个顶点,然后是第二个。 If both of them are selected it makes a new Line with those two vertices, but for some reason they get no values or something.
如果它们都被选中,它会用这两个顶点创建一条新线,但由于某种原因,它们没有任何值或其他东西。
it should be the other way:它应该是另一种方式:
pointed value of line and member of vertex线的点值和顶点成员
for(Line<Vertex> line : lines){
painter.drawLine(line->p1.x + 5, line->p1.y + 5, line->p2.x + 5, line->p2.y + 5);
}
if the class has如果班级有
T* pointerToMember;
T member;
you should get pointed member with ->
and member with .
您应该使用
->
获得指向成员,并使用.
obj->pointerToMember;
obj.member;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.