【发布时间】: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
main.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)
{
}
(问题已更新详细信息)
【问题讨论】:
-
为什么将对象命名为“类”? class 的 instance 是 OOP 中的 object