我在理解如何将“常规”代码转换为“面向对象”代码时遇到了一些困难。
我的代码是针对 Arduino 的,但是这个问题很笼统,所以没有 Arduino 的具体细节与这个问题相关。
在我的“常规”代码中,我只是导入一个库,使用一些参数调用构造函数来创建对象,然后调用方法 begin
#include <Adafruit_NeoPixel.h>
#define NPIXELS 10
#define PIN 3
#define FREQ 10000
void main() {
Adafruit_NeoPixel pixels(NPIXELS, PIN, FREQ);
pixels.begin();
}
现在,我正在构建自己的课程,并且在里面我想使用 Adafruit_NeoPixel,所以基本上我会这样做:
// MyDevice.h
class MyDevice {
public:
MyDevice(); // constructor
private:
// this fails, I cannot call the constructor with parameters here
// Adafruit_NeoPixel pixels(NPIXELS, PIN, FREQ);
// this compiles, so I just define pixels as an Adafruit_Neopixel object
Adafruit_NeoPixel pixels;
}
// MyDevice.cpp
#include "MyDevice.h"
MyDevice::MyDevice() { // constructor
// here I need to call the constructor of Adafruit_NeoPixel
// with the parameters NPIXELS, PIN and FREQ
// This fails
// no match for call to '(Adafruit_NeoPixel) (int, int, int)
this->pixels(NPIXELS, PIN, FREQ);
// This also fails
// no match for call to '(Adafruit_NeoPixel) (int, int, int)
pixels(NPIXELS, PIN, FREQ);
// This compiles, but I am not sure if here I am using the
// pixels object defined in the .h file or I am just
// creating a new object inside the constructor.
// If I remove the pixels definition from the h file it
// still compiles, which is suspicious
Adafruit_NeoPixel pixels(NPIXELS, PIN, FREQ);
}
所以,我的问题是:如何在我的类中创建对象像素并初始化它调用正确的构造函数(具有 3 个参数的构造函数:NUMPIXELS、PIN、FREQ)
谢谢