简体   繁体   中英

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). The program involves Springs and Vertices, both of which are classes. Springs apply a force to its two Vertices in a Hookean fashion.

Here is the code initializing three vertices, and two springs. S1 and S2 are springs, and V1 , V2 and V3 are vertices.

    //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. What really happens is that by writing S2.p0 = V2; , a copy of V2 is made. 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? Basically, I'm trying to assign references to V2 , rather than copies of V2 . How would I do this?

Change your definition of Spring to store Vertex pointers or references. 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

class Spring {
public:
    Vertex p0, p1;
}

but you want Spring to store a reference to a Vertex like in

class Spring {
public:
    Vertex &p0, &p1;
}

Using references as class members implies that Spring needs a constructor to initialize p0 and p1:

Spring(Vertex &v1, Vertex &v2) : p0(v0), p1(v1) {}

And you need to rewrite your Spring creation to

Spring S1(V1, V2);

You need to make sure that V1 lives at least as long as S1 so that the reference stays valid.

Of course Spring can also store pointers to Vertex instead if references. Pointers could be changed later, whereas the references can only be set during construction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM