从我的 class 调用对象构造函数

calling an Object constructor from my class

我在理解如何将“常规”代码转换为“面向对象”代码时遇到一些困难。

我的代码是针对 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();
}

现在,我正在构建自己的 class,并且我想在里面使用 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);
}

所以,我的问题是: 如何在我的 class 中创建对象像素并调用正确的构造函数(具有 3 个参数的构造函数:NUMPIXELS、PIN、FREQ)

对其进行初始化

谢谢

要从其他构造函数调用构造函数,请使用语法:

MyDevice::MyDevice() : pixels(NPIXELS, PIN, FREQ)
{
    // constructor of MyDevice
}

请仔细阅读您的 C++ 书籍。查找“Constructors and member initializer lists”部分。

MyDevice::MyDevice() : pixels{NPIXELS, PIN, FREQ}
{
}

如果您使用的是 C++11 或更新版本,则更喜欢大括号初始化而不是括号初始化。

另一个好的做法是不要使用宏(尽可能避免使用它们)。所以要定义常量使用 constconstexpr:

constexpr int NPIXELS = 10;
constexpr int PIN = 3;
constexpr int FREQ = 10000;