Arduino:在类的静态方法中访问静态变量

时间:2016-09-05 18:34:48

标签: class arduino static-methods static-variables

我想做的只是简单;

  • 使用静态类而不实例化(最好是a 单身人士)
  • 在一些静态中设置一些静态类变量 设定器/吸气剂。

它看起来非常简单,但我无法在互联网上找到任何示例。 不管我做了什么;未定义引用`Test :: _ pin'错误! 我不编译。

我的课程标题Test.h:

#ifndef Test_h
#define Test_h
#include "Arduino.h"

class Test
{
    public:
    Test(byte pin);
    static byte getPin();
    static byte _pin;    

    private:

};
#endif

我的班级代码Test.cpp:

#include "Test.h"

Test::Test (byte pin) {
    _pin = pin;
}

byte Test::getPin(){
    return _pin;
}

StaticClassTest.ino:

#include "Test.h"

void setup()
{
    Test(5);
    Serial.begin(9600);
    Serial.println(Test::getPin(), DEC);
}
void loop() { }

我已经尝试使用以下方式访问_pin:

byte Test::getPin(){
    return Test::_pin;  // did NOT work, reference error
}

理想情况下,_pin应该是私有的:并且可以通过我的getPin()访问; 但由于无法设置/获取此变量,因此我公开表示有更多机会。

这个简单的背景有什么问题?

如何在此课程中设置/获取此变量?

1 个答案:

答案 0 :(得分:2)

Test.cpp添加:

byte Test::_pin;

它会起作用。

它只是在类中声明,你必须为这个变量创建一个空间(通过添加定义)。

similar Q&A on SOall possibilities on cppreference.com

中的更多信息
相关问题