多态类的行为不符合预期

时间:2013-12-09 00:27:20

标签: c++ inheritance polymorphism arduino

我正在编写一些arduino代码,但事情并没有完全按计划进行 我在这做错了什么?我已经阅读并尝试了解虚拟功能,但也许我错过了一些东西。转到QUESTIONSHERE以获取我需要答案的实际问题,但首先是一些解释:

Classes RGBPixel和colorGenerator都派生自colorSource,它提供公共函数getR(),getG()和getB(),以便另一个像素或颜色修饰符可以获取其当前颜色的副本。
从colorGenerator派生的类实现颜色生成代码,以便它们可以生成自己的颜色,而RGBPixels具有colorSource *父成员,因此它们可以从colorGenerator或另一个RGBPixel获取颜色值。 在我的例子中,我有一个colorGenerator子类(CG_EmeraldWaters,它应该创建各种绿色和蓝色),然后是一个数组中的一些RGBPixel。 RGBPixels [0]应该从GC_EmeraldWaters的实例获取其值,而RGBPixels [1]从[1]中获取其值,从[1]中获取[2],从[n-1]获取[n]。像素似乎从它们的父项中拉出一种颜色就好了,但是链中的第一个像素没有正确查询colorGenerator,或者colorGenerator没有正确更新。

要更新colorGenerator,colorController类会监督整个过程:

colorController.h:

#ifndef _COLORCONTROLLER_H
#define _COLORCONTROLLER_H

#include <list>
#include "colorGenerator.h"
#include "RGBPixel.h"
#include "globals.h"
#include "Arduino.h"

unsigned long millis();

typedef std::list<colorGenerator> generatorList;

class colorController
{
    public:
    virtual bool refresh();
    protected:
    generatorList generators;
};

#endif //_COLORCONTROLLER_H

正如您所看到的,控制器有一个colorGenerators列表和方法来刷新它们(从loop()调用),除非在子类中重写,否则执行此操作:

bool colorController::refresh()
{
    for (generatorList::iterator it = generators.begin(); it != generators.end(); ++it)
    it->refresh();
    bool dirty = false;
    for (int i = NUM_OF_LEDS-1; i >= 0; --i)
    dirty |= RGBPixels[i].refresh();
    return dirty;
}

CC_Cascade类(派生自colorController)设置如下:

CC_Cascade.h

#ifndef _CC_CASCADE_H
#define _CC_CASCADE_H

#include "colorController.h"

class CC_Cascade : public colorController
{
    public:
        CC_Cascade();
        ~CC_Cascade();
};

#endif //_CC_CASCADE_H

CC_Cascade.cpp

#include "CC_Cascade.h"
#include "CG_EmeraldWaters.h"

CC_Cascade::CC_Cascade()
{
    colorGenerator * freshBubblingSpring = new CG_EmeraldWaters();
    generators.push_back(*freshBubblingSpring);
    RGBPixels[0].setParent(freshBubblingSpring);
    RGBPixels[0].setDelay(40);
    for (int i = 1; i < NUM_OF_LEDS; ++i)
    {
    RGBPixels[i].setParent(&RGBPixels[i-1]);
    RGBPixels[i].setDelay(500-(9*i)); //FIXME: magic number only works for 50ish pixels
    }
}

CC_Cascade::~CC_Cascade()
{
    //TODO: delete generators
}

到目前为止这么清楚? 让我提请你注意colorController :: refresh()函数。应该发生的是,每次调用它时,生成器列表中都有一个colorGenerator(因为CC_Cascade构造函数将它放在那里),这是一个CG_EmeraldWaters。当对此调用refresh()时(通过迭代器),它调用colorGenerator :: refresh(),后者又调用updateColor()。在CG_EmeraldWaters的情况下,这是覆盖的,因此应该调用CG_EmeraldWaters :: updateColor,给出绿松石色。使用一些串行写入语句来调试,我可以看到IN FACT colorGenerator :: updateColor()被调用,所以在这种情况下我会期望一个橙色,但这些都不会影响像素的颜色,这些都是保持CG_EmeraldWaters构造中设置的紫色。
稍微搞砸了,我将以下行添加到colorGenerator :: updateColor():RGBPixels[0].setColor(255,127,0); 而不是我希望的橙色,第一个像素在紫色和橙色之间快速交替,暗示(恕我直言)我的新代码行正在完成其工作,但随后像素再次从colorGenerator中拉出其原始的紫色,并且colorGenerator :: updateColor()不会改变colorGenerator的颜色(假设我没有得到编译错误,它改变了什么?)。

所以我的问题是:( QUESTIONSHERE)
1)我如何在colorGenerator :: updateColor()中更改colorSource :: currentR(/ G / B)的值,因为currentR(/ G / B)在colorSource中声明为protected并且colorGenerator直接从colorSource?
2)给定一个CG_EmeraldWaters的实例,如果在ColorGenerator中将updateColor()声明为virtual并在CG_EmeraldWaters中重写,我如何通过colorGenerator :: refresh()通过colorGenerator :: refresh()调用CG_EmeraldWaters :: updateColor ?,

以下是colorGenerator和CG_EmeraldWaters的代码:

colorSource.h:

#ifndef _COLORSOURCE_H
#define _COLORSOURCE_H

#include "Arduino.h"
#ifdef DEBUG
#include "colorGenerator.h" //FIXME: delete Me
#endif

//#define byte unsigned char
typedef byte colorStorage_t;

class colorSource
{
    public:
    colorSource();
        colorSource(colorStorage_t initialR, colorStorage_t initialG, colorStorage_t initialB);

    void setColor(colorStorage_t newR, colorStorage_t newG, colorStorage_t newB);
    //TODO: better implementation than this
    colorStorage_t getR();
    colorStorage_t getG();
    colorStorage_t getB();

    bool hasChanged();

    protected:
    colorStorage_t currentR;
    colorStorage_t currentG;
    colorStorage_t currentB;

    bool dirty;
#ifdef DEBUG
    friend colorGenerator; //FIXME: delete Me
#endif
};

#endif //_COLORSOURCE_H

colorSource.cpp:

#include "colorSource.h"

colorSource::colorSource()
{
    //nothing here
}

colorSource::colorSource(colorStorage_t initialR, colorStorage_t initialG, colorStorage_t initialB)
    :
    currentR(initialR),
    currentG(initialG),
    currentB(initialB)
{
    //intialised in the list
    Serial.println("Constructed Color Source with initial color");
}

void colorSource::setColor(colorStorage_t newR, colorStorage_t newG, colorStorage_t newB)
{
    currentR = newR;
    currentG = newG;
    currentB = newB;
}

colorStorage_t colorSource::getR()
{
    return currentR;
}

colorStorage_t colorSource::getG()
{
    return currentG;
}

colorStorage_t colorSource::getB()
{
    return currentB;
}

bool colorSource::hasChanged()
{
    return !dirty;
}

colorGenerator.h:

#ifndef _COLORGENERATOR_H
#define _COLORGENERATOR_H

#include "colorSource.h"
#ifdef DEBUG
#include "RGBPixel.h" //delete me, used for debugging!
#include "globals.h" //and me!
#endif

extern "C" unsigned long millis();

class colorGenerator : public colorSource
{
    public:
        colorGenerator(colorStorage_t initialR, colorStorage_t initialG, colorStorage_t initialB);
    bool refresh();

    protected:
    virtual void updateColor();

    unsigned long nextColorUpdate = 0;
    unsigned short delay = 40;
};

#endif //_COLORGENERATOR_H

colorGenerator.cpp:

#include "Arduino.h"

#include "colorGenerator.h"

colorGenerator::colorGenerator(colorStorage_t initialR, colorStorage_t initialG, colorStorage_t initialB)
    :
    colorSource(initialR,initialG,initialB)
{
    //intialised in the list
    //Serial.println("Constructed Color Generator");
}

bool colorGenerator::refresh()
{
#ifdef DEBUG
    Serial.print("colorGenerator::refresh()");
#endif
    if (millis() < nextColorUpdate)
    return false;
    nextColorUpdate = millis() + (unsigned long) delay;
    this->updateColor();
    return true;
}

void colorGenerator::updateColor() //this function gets called (even if it has been overridden in a child class), but the code in it doesn't have the desired effect
{
#ifdef DEBUG
    //Serial.print("colorGenerator::updateColor()");
    //RGBPixels[0].setColor(255,127,0);
#endif
    currentR = random(127,255);
    currentG = random(0,127);
    currentB = 0;
}

CG_EmeraldWaters.h:

#ifndef _CG_EMERALDWATERS_H
#define _CG_EMERALDWATERS_H

#include "colorGenerator.h"
#include "globals.h"
#include "RGBPixel.h"

class CG_EmeraldWaters : public colorGenerator
{
    public:
        CG_EmeraldWaters();

    protected:
        void updateColor();
};

#endif //_CG_EMERALDWATERS_H

CG_EmeraldWaters.cpp:

#include "Arduino.h"

#include "CG_EmeraldWaters.h"

CG_EmeraldWaters::CG_EmeraldWaters()
    :
    colorGenerator(255,0,255) //this color seems to stick! Changes made by updateColor() aren't propogated to the pixels.
{
    //initialised in list
    //Serial.println("Constructed Emerald Waters");
}

long random(long,long);

void CG_EmeraldWaters::updateColor() //this never seems to be called!
{
    currentR = 0;
    currentG = random(0,255);
    currentB = random(0,255);
}

最后,主草图文件:

#include "FastSPI_LED2.h"
#include <StandardCplusplus.h>

#include "colorController.h"
#include "RGBPixel.h"
#include "globals.h"
#include "CC_Cascade.h"

colorController * currentColorController;
RGBPixel RGBPixels[NUM_OF_LEDS];
struct CRGB ledString[NUM_OF_LEDS];

void setup()
{
#ifdef DEBUG
    //debugging:
    Serial.begin(9600);
    Serial.println("In Setup");
#endif

  // sanity check delay - allows reprogramming if accidently blowing power w/leds
    //delay(2000);
    LEDS.setBrightness(8);
    LEDS.addLeds<WS2801>(ledString, NUM_OF_LEDS);

    currentColorController = new CC_Cascade();
}

void writeValuesToString()
{
    for (int i = 0; i < NUM_OF_LEDS; ++i)
    ledString[i] = CRGB(RGBPixels[i].getR(),RGBPixels[i].getG(),RGBPixels[i].getB());
    LEDS.show();
}

void loop()
{
    static bool dirty = false; //indicates whether pixel values have changed since last hardware write
    //unsigned long lastHardwareWrite = 0; //time of last hardware write - only do this once per milisecond to avoid flicker (this method doesn't work, still flickers)

    dirty |= currentColorController->refresh();
    if (dirty)
    {
    dirty = false;
    writeValuesToString();
        delay(1); //to prevent flicker
    }
}

2 个答案:

答案 0 :(得分:5)

您的问题归因于所谓的object slicing。以下是:当您声明类型generatorList

的列表时
typedef std::list<colorGenerator> generatorList;

其成员仅限于colorGenerator中的内容。派生类的任何内容都不重要,所以当你按

colorGenerator * freshBubblingSpring = new CG_EmeraldWaters();
generators.push_back(*freshBubblingSpring);

CG_EmeraldWaters中不属于colorGenerator的{​​{1}}部分被“切掉”;您的最终版本为colorGenerator

上面链接的维基百科文章中描述了其原因。要解决此问题,请更改列表以包含指向colorGenerator实例的指针,最好是smart pointers。然后切片问题将不再相关:

typedef std::list<unique_ptr<colorGenerator> > generatorList;
...
unique_ptr<colorGenerator> freshBubblingSpring(new CG_EmeraldWaters());
generators.push_back(freshBubblingSpring);

答案 1 :(得分:0)

  1. 你应该能够从派生类中调用基类的private和protected方法,除非我遗漏了什么。

  2. 要调用覆盖方法(例如,虚拟foo()在类Base中定义并在类Derived中重写),您可以通过在代码中调用derivedObj.Base::foo()来访问Base方法。