我正在尝试在网上遵循this的示例,该示例将我带入以下代码:
EquipmentCollection.h(头文件)
#ifndef EQUIMENTCOLLECTION_H_
#define EQUIMENTCOLLECTION_H_
#include "Equipment.h"
#include <vector>
class EquipmentCollection : public Equipment {
public:
static void add( Equipment* );
static vector<Equipment*>& get();
~EquipmentCollection();
private:
static vector<Equipment*>* equipmentList;
};
#endif /* EQUIMENTCOLLECTION_H_ */
EquipmentCollection.cpp(源文件)
#include "EquipmentCollection.h"
void EquipmentCollection::add( Equipment* equipment ) {
if( equipmentList == NULL ) {
equipmentList = new vector<Equipment*>();
}
equipmentList->push_back( equipment );
}
vector<Equipment*>& EquipmentCollection::get() {
return *equipmentList;
}
EquipmentCollection::~EquipmentCollection() {
delete( equipmentList );
}
我的错误是源文件上的
return *equipmentList;
,这给了我undefined reference to "EquipmentCollection::equipmentList"
错误。我不知道为什么会给我这个错误。 最佳答案
您尚未初始化静态成员。您应该在CPP文件中添加以下代码:
vector<Equipment*>* EquipmentCollection::equipmentList = nullptr;
另外,您的代码还有其他问题:
EquipmentCollection
的任何实例,因此将永远不会调用您的析构函数并且也不会释放设备。 EquipmentCollection::get
,则::add
将具有undefined behavior,原因是(8.3.2 / 4“References”):