Domanda

Seems like a simple question, but my knowledge of C++ is sadly not very good.

So I have Joint declared as a class in another file. I want another class named Dancer to accept Joint instance from outside and save it in it's own instance.

I have something like this so far.

// Dancer.h
class Dancer {
  public:
    Joint joint;
    void setJoint(Joint newJoint);
    void animate();
}

// Dancer.cpp
Dancer::setJoint(Joint newJoint) {
  joint = newJoint;
}
Dancer::animate() {
  joint.moveTo(random(90));
}

// MainArduinoSketch.ino
Joint frontLeftJoint;
void setup() {
  dancer.setJoint(frontLeftJoint);
}

The problem is that my manipulation of the joint no longer works, though I get no errors or crashes. I clearly have an instance, which keeps values and responds to methods, but it's not the same instance. It's acting like I cloned the joint, rather passed the joint around.

I have a hunch I probably need some pointers somewhere to keep the reference, but I'm not sure exactly what needs to be a pointer, and how to call methods on instances referenced though a pointer.

So how can my code above be changed so that an instance of Dancer can get passed an instance of Joint and have it be the exact same instance of joint?

È stato utile?

Soluzione

If you wish to talk about the exact same instance, you need to indeed use a reference or a pointer (they are fairly similar in what happens under the hood).

The choice falls to a pointer in this case, because you can only initialize a reference, but not set its value later on anymore. Since you have a setJoint, this is clearly a reason to use a pointer.

To keep the rest of the code mostly the same, we will let setJoint take a reference argument however, and then take its address to gain access to a pointer to the memory location that was passed by reference to the function.

When accessing members (be they data or function) of objects to which we have a pointer, there are two options: You can either dereference the pointer and then use the resulting object as you normally would, or you can use the -> operator to do this in one step.

Putting everything together, this is the result:

// Dancer.h
class Dancer {
  public:
    Joint* joint;
    void setJoint(Joint& newJoint);
    void animate();
}

// Dancer.cpp
Dancer::setJoint(Joint& newJoint) {
  joint = &newJoint;
}
Dancer::animate() {
  joint->moveTo(random(90));
}

// MainArduinoSketch.ino
Joint frontLeftJoint;
void setup() {
  dancer.setJoint(frontLeftJoint);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top