代码之家  ›  专栏  ›  技术社区  ›  Nasenbaer

C++在ARDUIO中创建类实例

  •  0
  • Nasenbaer  · 技术社区  · 4 年前

    如何创建一个类的多个实例?

    我想有几个类,都像C#中的接口,使用相同的结构,但有不同的实例。

    如果我启动以下构造,它会告诉我错误,该类没有实例化的“KEY”。

    我正在使用struct StateController 但这只是为了展示环境,问题已经出现了 String Key .

    基础H

        #ifndef _BASE_H
    #define _BASE_H
    #include <Arduino.h>
    #include "StateController.h"
    
    class _Base
    {
    public:
        _Base();
        void Init(StateController *stateController);
        void Update(StateController *stateController);
    
    private:
        String Key;
    };
    
    extern _Base _BaseInstance;
    #endif
    

    主要的cpp

    void setup()
    {
    // Here I can only access the _BaseInstance. 
    // If I create a h file for each Class1.h/Class2.h/Class3.h I can access
    // But throws exception because "Key" has multiple definitions.
      Class1.Init(&stateController);
      Class2.Init(&stateController);
      Class3.Init(&stateController);
    }
    

    _基地。cpp

    #include "StateController.h"
    #include <Arduino.h>
    #include "_Base.h"
    
    //
    //
    //
    
    
    StateItem stateItem;
    
    _Base::_Base()
    {
        Key = "Class 1";
    }
    
    void _Base::Init(StateController *stateController)
    {
        stateItem = stateController->Add(Key);
    }
    
    void _Base::Update(StateController *stateController)
    {
    }
    

    (问题更新细节)

    0 回复  |  直到 4 年前
        1
  •  0
  •   Marion    4 年前

    很难说是怎么回事,因为你还没有在Class1中共享代码。h、 2班。h、 还有3班。h、 您也没有告诉我们Class1、Class2和Class3是在哪里声明的。这三个对象是从_Base继承的类的实例吗?还是仅仅是_Base的例子?你需要多态性,还是只使用_基类就足够了?

    听起来你可能把对多态性的需求和对同一类的不同实例的需求混为一谈,你的代码可能反映了这一点。

    将构造函数更改为采用单个字符串参数,然后将其分配给Key,这样就足够了吗?你可以这样做:

    基础H

    #ifndef _BASE_H
    #define _BASE_H
    #include <Arduino.h>
    #include "StateController.h"
    
    class _Base
    {
    public:
        _Base(String _Key);
        void Init(StateController *stateController);
        void Update(StateController *stateController);
    
    private:
        String Key;
    };
    
    extern _Base _BaseInstance;
    #endif
    

    然后将构造函数定义为:

    基础cpp

    _Base::_Base(String _Key) :
        Key(_Key) {}
    

    然后相应地初始化各个对象:

    主要的cpp

    _Base Class1 ("Class 1");
    _Base Class2 ("Class 2");
    _Base Class3 ("Class 3");
    
    void setup()
    {
      Class1.Init(&stateController);
      Class2.Init(&stateController);
      Class3.Init(&stateController);
    }