类实例的C++/向量作为另一个类的属性

C++/ vector of class instances as property of another class

本文关键字:属性 另一个 实例 C++ 向量      更新时间:2023-10-16

我正在尝试创建具有私有属性_testItems的类(PgWeightTestItemSet)。_testItems是另一个类(PgWeightTestItem)的实例的std::vector。

PgWeightTestItem 的标头包含在 PgWeightTestItemSet.h 中。

我在Arduino IDE中进行代码检查后出现错误:

error: 'PgWeightTestItem' was not declared in this scope std::vector <PgWeightTestItem> _testItems;

所以我的问题是:

  • 是否可以将类实例的向量声明为另一个类的属性
  • 如果可能的话,我做错了什么?

代码如下:

PgWeightTestItemSet.h

#ifndef PgWeightTestItemSet_h
#define PgWeightTestItemSet_h
#include "Arduino.h"
#include <PgWeightTestItem.h>
class PgWeightTestItemSet {
public:
PgWeightTestItemSet(std::vector<float> & referenceAv, std::vector<float> & referenceMin, std::vector<float> & referenceMax, bool cumulative);
/*other public properties and methods*/
private:       
std::vector <PgWeightTestItem> _testItems;
/*other private properties and methods*/
};
#endif

PgWeightTestItem.h

#ifndef PgWeightTestItem_h
#define PgWeightTestItem_h
#include "Arduino.h"
class PgWeightStandards {
public:
PgWeightStandards(float & referenceAv, float & referenceMin, float & referenceMax);
/*public properties*/
private:
/*private properties*/
};
#endif

Arduino_project.ino

#include <PgWeightTestItemSet.h>
//other arduino code bellow

目录结构

/root/
/root/Projects/ArduinoProject/Arduino_project.ino
/root/libraries/PgWeightTestItem/
/root/libraries/PgWeightTestItem/PgWeightTestItem.h
/root/libraries/PgWeightTestItem/PgWeightTestItem.cpp
/root/libraries/PgWeightTestItemSet/
/root/libraries/PgWeightTestItem/PgWeightTestItemSet.h
/root/libraries/PgWeightTestItem/PgWeightTestItem.cpp

您在PgWeightTestItem.h 中定义的类称为PgWeightStandards而不是PgWeightTestItem。通过重命名其中一个,您应该没问题。PgWeightTestItem.h 可以如下所示:

#ifndef PgWeightTestItem_h
#define PgWeightTestItem_h
#include "Arduino.h"
class PgWeightTestItem {
public:
PgWeightTestItem(float & referenceAv, float & referenceMin, float & referenceMax);
/*public properties*/
private:
/*private properties*/
};
#endif