将指针或引用传递给对象的构造函数

问题描述 投票:0回答:1

对 C++ 相当陌生,并且在引用与指针方面存在问题。下面的代码是一个简单电机的类并工作。我想在构造函数中传递引脚扩展器,但似乎无法使其工作。

我用 &expander 调用这些方法。我尝试为扩展器添加 setter 和 getter,但这似乎不起作用。

这是最好的方法吗?我可以将其传递给构造函数吗?

这是标题

#ifndef PMotor_H
#define PMotor_H

#include <Arduino.h>
#include <PCF8575.h>

class PMotor {
private:

  uint8_t pinA;
  uint8_t pinB;
  uint8_t direction;


public:
  // Constructor
  PMotor(uint8_t pinA, uint8_t pinB);

  // Turn the motor on with a specified speed.
  void on(uint8_t direction, PCF8575 *expander);

  // Turn the motor on with a specified speed, for a given time.
  void on(uint8_t direction, int millisec, PCF8575 *expander);

  // Turn the motor off.
  void off(PCF8575 *expander);
  bool movingCW();
  bool movingCCW();


};

#endif

这就是人民党

#include "PMotor.h"
#include <PCF8575.h>

bool mCW;
bool mCCW;

PMotor::PMotor(uint8_t pinA, uint8_t pinB) {
  this->pinA = pinA;
  this->pinB = pinB;
}



void PMotor::on(uint8_t direction, PCF8575 *expander) {

  if (direction == 0) {
    expander->write(pinA, HIGH);
    expander->write(pinB, LOW);
    mCW = true;
    mCCW = false;

  } else {
    expander->write(pinA, LOW);
    expander->write(pinB, HIGH);
    mCW = false;
    mCCW = true;
  }
}

void PMotor::on(uint8_t direction, int millisec, PCF8575 *expander) {
  this->on(direction, expander);
  delay(millisec);
  this->off(expander);
}

void PMotor::off(PCF8575 *expander) {
  expander->write(this->pinA, LOW);
  expander->write(this->pinB, LOW);
  mCW = false;
  mCCW = true;
}

bool PMotor::movingCW() {
  return mCW;
}

bool PMotor::movingCCW() {
  return mCCW;
}
c++ pointers ref
1个回答
0
投票

我想在构造函数中传递引脚扩展器,但似乎无法使其工作。

这是一种通过引用获取扩展器但存储指针的方法。通过引用来获取它可以确保您不会得到

nullptr
- 将其存储为指针可以轻松地将复制/移动语义添加到您的类中。

class PMotor {
private:
    PCF8575* expander; // store a pointer
    uint8_t pinA;
    uint8_t pinB;
    uint8_t direction;

public:
    // Constructor - takes an expander by reference:
    PMotor(PCF8575& expander, uint8_t pinA, uint8_t pinB);

    // No expander needed in the rest:

    // Turn the motor on with a specified speed.
    void on(uint8_t direction);

    // Turn the motor on with a specified speed, for a given time.
    void on(uint8_t direction, int millisec);

    // Turn the motor off.
    void off();

    bool movingCW();
    bool movingCCW();
};

然后,成员函数的实现看起来非常像它们已经做的 - 只是删除了

PCF8575*

构造函数例如可以简单地是:

PMotor::PMotor(PCF8575& expander, uint8_t pinA, uint8_t pinB) :
    expander(&expander), // store the pointer
    pinA(pinA),
    pinB(pinB)
{}
© www.soinside.com 2019 - 2024. All rights reserved.