[英]How can I assign a class instance by reference in C++?
I've written an SDL graphics program in C++ (it's about 300 lines, so I will try to summarize). 我已经用C ++写了一个SDL图形程序(大约300行,因此我将尝试进行总结)。 The program involves Springs and Vertices, both of which are classes. 该程序涉及Springs和Vertices,它们都是类。 Springs apply a force to its two Vertices in a Hookean fashion. Springs以Hookean方式对其两个顶点施加力。
Here is the code initializing three vertices, and two springs. 这是初始化三个顶点和两个弹簧的代码。 S1
and S2
are springs, and V1
, V2
and V3
are vertices. S1
和S2
是弹簧,而V1
, V2
和V3
是顶点。
//Initialize vertices
Vertex V1;
V1.pos.x = 100;
V1.pos.y = 300;
Vertex V2;
V2.pos.x = 200;
V2.pos.y = 200;
Vertex V3;
V3.pos.x = 300;
V3.pos.y = 100;
//Initialize springs
Spring S1;
S1.p0 = V1;
S1.p1 = V2;
Spring S2;
S2.p0 = V2;
S2.p1 = V3;
The intention is that V2
is connected to both S1
and S2
, and that the two springs are connected to each other through this vertex. 目的是将V2
连接到S1
和S2
,并且两个弹簧通过此顶点相互连接。 What really happens is that by writing S2.p0 = V2;
真正发生的是通过写S2.p0 = V2;
, a copy of V2 is made. ,制作了V2的副本。 I made this illustration to clarify. 我做了这个插图来澄清。
So here's my question: How can I edit the above code so that I get the intended result? 所以这是我的问题:如何编辑上面的代码以便获得预期的结果? That is, how can I assign p0
and p1
to the springs, such that they refer to the original objects? 也就是说,如何为弹簧分配p0
和p1
,以便它们引用原始对象? Basically, I'm trying to assign references to V2
, rather than copies of V2
. 基本上,我试图将引用分配给V2
,而不是V2
副本 。 How would I do this? 我该怎么做?
Change your definition of Spring
to store Vertex
pointers or references. 更改Spring
的定义以存储Vertex
指针或引用。 Pointers will give you more flexibility to do things move a spring and attach to a different vertex: 指针将为您提供更大的灵活性,使事情可以移动弹簧并附加到其他顶点:
struct Spring {
Vertex* p0;
Vertex* p1;
};
And then set them like this: 然后像这样设置它们:
Spring S1;
S1.p0 = &V1;
S1.p1 = &V2;
It seems like your class Spring stores a Vertex like in 看来您的班级Spring像这样存储了一个Vertex
class Spring {
public:
Vertex p0, p1;
}
but you want Spring to store a reference to a Vertex like in 但您希望Spring像这样存储对Vertex的引用
class Spring {
public:
Vertex &p0, &p1;
}
Using references as class members implies that Spring needs a constructor to initialize p0 and p1: 将引用用作类成员意味着Spring需要一个构造函数来初始化p0和p1:
Spring(Vertex &v1, Vertex &v2) : p0(v0), p1(v1) {}
And you need to rewrite your Spring creation to 而且您需要将Spring创作重写为
Spring S1(V1, V2);
You need to make sure that V1 lives at least as long as S1 so that the reference stays valid. 您需要确保V1的寿命至少与S1一样长,以使参考保持有效。
Of course Spring can also store pointers to Vertex instead if references. 当然,如果有引用,Spring也可以存储指向Vertex的指针。 Pointers could be changed later, whereas the references can only be set during construction. 以后可以更改指针,而引用只能在构造期间设置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.