【问题标题】:Arduino: initialise custom object in constructorArduino:在构造函数中初始化自定义对象
【发布时间】:2014-01-22 08:13:53
【问题描述】:

我创建了 1 个包含 2 个类的库。类 Wave 和类 LED 灯。在第二类构造函数中,我试图在没有任何运气的情况下填充第一类对象的数组。

这是我真实代码的一些部分。 h 文件:

static const int numberOfWaves = 20;

class Wave
{
public:
    Wave(int speed, int blockSize, int ledCount, int lightness,int startCount); // Constructor

private:

};

// ------------------------------------------------------------------------------------------- //
class LEDLamps
{
public:
    LEDLamps(int8_t lampCount, int8_t dataPin, int8_t clockPin); //Constructor

private:
    Wave waveArray[numberOfWaves];
};

.cpp 文件

Wave::Wave(int speed, int blockSize, int ledCount, int lightness, int startCount) //Constructor
{ 
           // Doing some stuff...
}

// ------------------------------------------------------------------------------------------- //
LEDLamps::LEDLamps(int8_t lampCount, int8_t dataPin, int8_t clockPin) //Constructor
{ 
    int i;
    for (i = 0; i < numberOfWaves; i++) {
        waveArray[i] = Wave(10,2,25,150,100);
    }
}

错误信息:

LEDLamps.cpp: In constructor 'LEDLamps::LEDLamps(int8_t, int8_t, int8_t)':
LEDLamps.cpp:66: error: no matching function for call to 'Wave::Wave()'
LEDLamps.cpp:14: note: candidates are: Wave::Wave(int, int, int, int, int)
LEDLamps.h:23: note:                 Wave::Wave(const Wave&)

我从该错误消息中了解到参数错误但我发送 5 个整数并且构造函数被定义为接收 5 个整数?所以我一定是我做错了什么......

【问题讨论】:

    标签: c++ arrays constructor arduino arduino-ide


    【解决方案1】:

    错误告诉你究竟出了什么问题,没有Wave::Wave() 方法。您需要 Wave 类的默认构造函数才能创建它的数组。如果 Wave 类包含重要数据,您可能还想创建一个复制赋值运算符。

    问题是数组是在LEDLamps 构造函数的主体运行之前构造的,所以当在LEDLamps 构造函数的主体中时,数组是完全构造的,而你正在做的是赋值(使用自动生成的复制赋值运算符)。


    不幸的是,默认的 Arduino C++ 库非常有限,至少在“标准”C++ 功能方面如此。有libraries that helps,如果可以使用这样的库,您可以改用std::vector,这将允许您在构造函数initializer-list 中构造向量:

    class LEDLamps
    {
        ...
        std::vector<Wave> waveVector;
    };
    
    ...
    
    LedLamps::LEDLamps(...)
        : waveVector(numberOfWaves, Wave(10,2,25,150,100))
    {
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-06
      • 1970-01-01
      • 2013-05-23
      • 1970-01-01
      • 1970-01-01
      • 2021-09-10
      • 1970-01-01
      • 2012-03-05
      • 1970-01-01
      相关资源
      最近更新 更多