开发者

Redeclaration of variable

When I run Setup() I expect to see a 't' in my console, followed by multiple 'x' ch开发者_如何学Pythonaracters. However it returns just multiple 't' chars. It's like my retrn never gets overwrited. Please see codesample below:

class Returner
{
    public:
        Returner(){}

        char test()
        {
        }
};

class TReturner: public Returner
{
    public:
        TReturner(){}

        char test()
        {
            return 't';
        }
};

class XReturner: public Returner
{
    public:
        XReturner(){}

        char test()
        {
            return 'x';
        }
};

void setup()
{
    Serial.begin(9600);

    TReturner t = TReturner();
    Returner * retrn = &t;

    while(1)
    {
        Serial.print( retrn.test());

        XReturner x = XReturner();
        retrn = &x;

        _delay_ms(500);
    }
}


I can't 100% explain that behaviour - I'd expect you wouldn't get any characters printed as it'd be using Returner::test - but if you're overriding a function in C++ you need to declare it virtual in the base class:

class Returner 
{
  public:   
    Returner(){}
    virtual char test()
    {    
    }
};

Without test being virtual, the line

Serial.print( retrn.test() );

(don't you mean retrn->test()?) will just pick one implementation of test and use it always. As above I'd expect this to be the empty Returner::test(). You may also either need to make Returner::test abstract

    virtual char test() = 0;

or return some value if you're leaving it with a function body.


setup() will be called once by the bootloader. (do not create an infinite loop inside of it)
You should define a loop() function, it too will be called by the bootloader an 'infinite' number of times.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜