本文介绍了构造函数类需要参数但想将其用作属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一堂课

#include <SPI.h>
#include <Keypad.h>
#include "Debug.h"

class Keyblock {
  private:
    Debug debug;
    Keypad keypad;

  public:
    void init(byte * keypadRowPins, byte * keypadColPins, Debug &debug);
    void read();
};


void Keyblock::init(byte * keypadRowPins, byte * keypadColPins, Debug &debug) {
  this->debug = debug;
  char keys[4][3] = {
    {'1','2','3'},
    {'4','5','6'},
    {'7','8','9'},
    {'*','0','#'}
  };
  keypad = Keypad(makeKeymap(keys), keypadRowPins, keypadColPins, 4, 3);
}

void Keyblock::read() {
  char key = keypad.getKey();
  debug.message(key);
}

使用 arduino 键盘库@https://playground.arduino.cc/Code/Keypad/

that uses the arduino keypad library @ https://playground.arduino.cc/Code/Keypad/

但是它发布错误(在帖子底部)因为(我相信)键盘构造函数需要参数.有什么技巧可以使我的班级工作或其他模式可以防止出现此问题?

However it is posting errors (at bottom of post) because (I believe) the Keypad constructor requires parameters. Is there a trick to making this work or another pattern for my class that will prevent this issue?

感谢您提供的任何帮助.我对这一切都很陌生.

Thanks for any help you can provide. I am very new at all of this.

In file included from sketch\Box.h:7:0,
                 from D:\source\Main\Main.ino:2:
sketch\Keyblock.h:8:7: note: 'Keyblock::Keyblock()' is implicitly deleted because the default definition would be ill-formed:
 class Keyblock {
       ^~~~~~~~
Keyblock.h:8:7: error: no matching function for call to 'Keypad::Keypad()'
In file included from sketch\Keyblock.h:5:0,
                 from sketch\Box.h:7,
                 from D:\source\Main\Main.ino:2:
C:\Users\campo\Documents\Arduino\libraries\Keypad\src/Keypad.h:78:2: note: candidate: Keypad::Keypad(char*, byte*, byte*, byte, byte)
  Keypad(char *userKeymap, byte *row, byte *col, byte numRows, byte numCols);
  ^~~~~~
C:\Users\----\Documents\Arduino\libraries\Keypad\src/Keypad.h:78:2: note:   candidate expects 5 arguments, 0 provided

推荐答案

不是技巧,但由于 Keypad 没有默认构造函数,您需要在 您的Keyblock 构造函数的成员初始值设定项列表.

Not a trick, but since Keypad doesn't have a default constructor, you need to initialize it in the member initializer list of your Keyblock constructor(s).

示例:

class Keyblock {
private:
    static constexpr byte ROWS = 4;
    static constexpr byte COLS = 3;

    char keys[ROWS][COLS] = {
      {'1','2','3'},
      {'4','5','6'},
      {'7','8','9'},
      {'*','0','#'}
    };

    // put your pins in these arrays:
    byte keypadRowPins[ROWS] = { 9, 8, 7, 6 };
    byte keypadColPins[COLS] = { 12, 11, 10 };

    Keypad keypad;

public:
    Keyblock(); // add a user-defined default constructor
};

Keyblock::Keyblock() : // member init-list between `:` and the body of the constructor
    keypad(makeKeymap(keys), keypadRowPins, keypadColPins, ROWS, COLS)
{}

这篇关于构造函数类需要参数但想将其用作属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 13:54