【问题标题】:C++ in Arduino create instances of classArduino中的C++创建类的实例
【发布时间】:2021-12-29 16:18:41
【问题描述】:

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

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

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

我正在使用结构StateController,但这只是为了展示环境,问题已经在String Key

Base.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

ma​​in.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);
}

_Base.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)
{
}

(问题已更新详细信息)

【问题讨论】:

  • 为什么将对象命名为“类”? classinstance 是 OOP 中的 object

标签: c++ arduino


【解决方案1】:

很难知道发生了什么,因为您没有共享 Class1.h、Class2.h 和 Class3.h 中的代码,也没有向我们展示 Class1、Class2 和 Class3 的声明位置。这三个对象本身是从_Base 继承的类的实例吗?或者它们只是 _Base 的实例?您需要多态性,还是仅使用 _Base 类就足够了?

听起来您可能会将对多态性的需求与对同一类的不同实例的需求混为一谈,而您的代码可能会反映这一点。

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

Base.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

然后将构造函数定义为:

Base.cpp

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

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

ma​​in.cpp

_Base Class1 ("Class 1");
_Base Class2 ("Class 2");
_Base Class3 ("Class 3");

void setup()
{
  Class1.Init(&stateController);
  Class2.Init(&stateController);
  Class3.Init(&stateController);
}

【讨论】:

  • 有时很难找到最好的方法来紧凑地询问和仅发布相关部分。在那种情况下,我会学习,我需要分享更多细节。感谢您的回答,我会尽力理解并更新我的问题。
  • 我的问题出在你的_Base::_Base(String _Key) :。如果可能的话,我不想在构造函数中将 Key 设置为字符串,我想在 cpp 文件中设置它。例如 1 类。但是后来我遇到了所描述的编译器问题。是我错了还是我没有分享足够的细节?
  • 为什么?我看不出这样做的目的。您的所有对象都是从 _Base 类继承的不同类的实例吗?如果是这样,为什么?能否分享一下声明和定义的代码,例如Class1?
猜你喜欢
  • 2022-12-22
  • 2012-01-05
  • 2016-05-30
  • 1970-01-01
  • 2012-08-24
  • 1970-01-01
  • 1970-01-01
  • 2013-11-16
  • 2013-08-10
相关资源
最近更新 更多