我有一个代表如此定义的坐标系的类:
CoordinateSystem.hpp:
#ifndef COORDINATESYSTEM_H
#define COORDINATESYSTEM_H
#include <string>
class CoordinateSystem
{
protected:
std::string name;
public:
CoordinateSystem(std::string csName);
std::string get_Name(void);
};
#endif
我还有另一个类,我想用它作为所有已注册坐标系的容器:
CoordinateSystems.hpp:
#ifndef COORDINATESYSTEMS_H
#define COORDINATESYSTEMS_H
#include <string>
#include <map>
#include "CoordinateSystem.hpp"
class CoordinateSystems
{
private:
std::map<std::string, CoordinateSystem*> csMap;
public:
bool Register(std::string name, CoordinateSystem* cs);
CoordinateSystem* get_CoordinateSystem(std::string name);
};
#endif
但是,由于目前已设置,因此需要我手动注册所有CoordinateSystems,如下所示:
main.cpp中:
#include <iostream>
#include <string>
#include "CoordinateSystems.hpp"
#include "CoordinateSystem.hpp"
int main(void)
{
CoordinateSystems csReg;
CoordinateSystem helio_eclip("HeliocentricEcliptic");
csReg.Register(helio_eclip.get_Name(), &helio_eclip);
CoordinateSystem* helio_eclip_ref = csReg.get_CoordinateSystem("HeliocentricEcliptic");
std::cout << helio_eclip_ref->get_Name() << std::endl;
return 0;
}
我想在创建时自动注册所有CoordinateSystem对象,但我不确定最好的方法。我确实想过添加如下内容:
CoordinateSystems.hpp:
extern CoordinateSystems csReg;
CoordinateSystems.cpp:
CoordinateSystems csReg;
这将包含在任何包含CoordinateSystems.hpp标头的文件中,这将允许我在其构造函数中注册所有CoordinateSystem对象,如下所示:
CoordinateSystem.cpp:
#include "CoordinateSystems.hpp"
CoordinateSystem::CoordinateSystem(std::string csName): name(csName)
{
csReg.Register(this->name, this);
}
这是否可以接受?或者我有一个更好的解决方案吗?