在C++中,你可以为类对象使用不同的常量吗?

问题描述 投票:0回答:1

我遇到一个类,它的唯一目的是创建闪烁的LED。他将这个类用于2个对象,这2个对象有不同的闪烁间隔。我开始思考如何使用常量,但没有想到。

是否可以使用const int与构造函数相结合,为对象使用不同的常量?

我知道const int要在声明它的地方初始化,所以我猜测答案是 "不可以

如果没有,有没有变通的办法来实现同样的事情?那就是对同一类型的不同对象使用不同的常量(所以内存使用量少)。

问题中使用的平台是arduino IDE和一个atmega328P.可能是编译器识别出变量实际上是作为常量使用的,并将其作为常量处理?

.h

class   BlinkingLed
{
private:
    int   blPin;
    short blinkInterval; // <-- the contant
    bool  blinking;
    bool  ledOn;
    long  lastTime;

public:
    BlinkingLed(int, int);
    void setBlinkInterval(int); // never used, should not exist
    int  getBlinkInterval();    // never used, should not exist
    void setLedOn(bool);
    bool getLedOn();
    void attachPin();
    void heartBeat();
};

.h

BlinkingLed::BlinkingLed(int aPin, int aBlinkInterval) // constructor
{
    blPin = aPin;
    blinking = false;
    ledOn = false;
    blinkInterval = aBlinkInterval; // <-- the contant
}

对象是用这一行做的。aki类需要2个BlinkLed对象。

AKI aki(new BlinkingLed(23,333), new BlinkingLed(22,667), 24); // Red blinks 90/minute, green 45/minute

这就是 aki 的构造函数。

AKI::AKI(BlinkingLed *aRedLight, BlinkingLed *aGreenLight, int aBellPin)
{
    redLight = aRedLight;
    greenLight = aGreenLight;
    bellPin = aBellPin;
}

333和367是存储在变量中的 我想让它们变成常量以保存内存空间。我该怎么做呢?

c++ arduino const
1个回答
2
投票

总结一下讨论,并纠正一些你的错误假设。

class   BlinkingLed {
private:
    const byte   blPin;  // This should definitely be const
    const unsigned short blinkInterval; // <-- the desired constant (why?)
    bool  blinking;
    bool  ledOn;
    unsigned long  lastTime;

public:
    BlinkingLed(byte pin, unsigned short interval) 
       : blPin(pin), blinkInterval(interval)  {}

    // void setBlinkInterval(int); // impossible for a const Interval

    void init() {pinMode(blPin, OUTPUT);}  // should not be done in a c'tor
    void run(); // to be called as often as possible for a smooth heartbeat

    unsigned short  getBlinkInterval() {return blinkInterval;}  // why not
    void setLed(bool); // stops blinking
    bool isLedOn();
    void heartBeat();  // start blinking
};

另外,数据类型 int 通常都会责怪你没有想到。)

© www.soinside.com 2019 - 2024. All rights reserved.