문제

What I would like to do is similar to this (working):

class Claw {
  public:
    Claw(int pin);
  private:
    int pin;
  };

Claw::Claw(int pinNumber) {
  pin = pinNumber;
  }

But I want to do it with classes instead of basic types. I want to define the class in the private section (so I can use it on all the object) and execute the AccelStepper constructor in the Wheel constructor. I've tried these two solutions and they both give different errors:

class Wheel {
  public:
    Wheel(int pin);
  private:
    AccelStepper stepper;
  };

Wheel::Wheel(int pinNumber) {

  // This doesn't work
  AccelStepper stepper(AccelStepper::DRIVER, pinNumber, 1);

  // This also doesn't work
  stepper(AccelStepper::DRIVER, pinNumber, 1);
  }

How can I achieve what I'm trying to do?

Note that this works, but I cannot pass the pin number then:

class Wheel {
  public:
    Wheel();
  private:
    AccelStepper stepper(5);
  };

Wheel::Wheel() {
  }
도움이 되었습니까?

해결책

You do it with a member initialization list:

Wheel::Wheel(int pinNumber)
    : stepper(AccelStepper::DRIVER, pinNumber, 1)
{
}

다른 팁

In your header:

class Wheel
{
public:
    class Stepper; // Forward declaration of embedded class

    Wheel();
    Stepper& stepper() { return *_pStepper; }

private:

    Stepper* _pStepper;
};

In your implementation:

class Wheel::Stepper
{
public:
    void accelerate() {}
};

Wheel::Wheel()
    : _pStepper( new Stepper() )
{
    stepper().accelerate();
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top