如何解决从我的课程中调用对象构造函数
我在理解如何将“常规”代码转换为“面向对象”代码时遇到一些困难。
我的代码是针对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,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,FREQ);
// This also fails
// no match for call to '(Adafruit_NeoPixel) (int,int)
pixels(NPIXELS,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,FREQ);
}
所以,我的问题是: 如何在类中创建对象像素并调用正确的构造函数(具有3个参数的对象:NUMPIXELS,PIN,FREQ)对其进行初始化
谢谢
解决方法
要从其他构造函数调用构造函数,请使用以下语法:
MyDevice::MyDevice() : pixels(NPIXELS,PIN,FREQ)
{
// constructor of MyDevice
}
,
请更仔细地阅读C ++书。查找“ Constructors and member initializer lists”部分。
MyDevice::MyDevice() : pixels{NPIXELS,FREQ}
{
}
并且如果您使用的是C ++ 11或更高版本,则比括号初始化更喜欢大括号初始化。
另一个好的做法是不使用宏(尽可能避免使用宏)。因此,使用const
或constexpr
来定义常量:
constexpr int NPIXELS = 10;
constexpr int PIN = 3;
constexpr int FREQ = 10000;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。