我正在尝试为米和公里创建单位。然后我想要相应地总结和转换它们。我知道boost :: units库已经有了SI系统,但是我想从头开始创建,因为之后我需要为我的项目创建自己的系统(所以我这样做是为了学习)。 我的目的是宣布“长度”变量,可以使用单位进行修改:比如我想写创建用户定义的转换
Length xLength1 = 5350 * Meters + 2 Kilometers;
为此,我创建了length.h文件,其中包含定义米和公里,并在最后,我宣布这两个单位之间的换算:
#ifndef LENGTH_H_
#define LENGTH_H_
#include <boost/units/base_dimension.hpp>
#include <boost/units/base_unit.hpp>
#include <boost/units/scaled_base_unit.hpp>
#include <boost/units/quantity.hpp>
#include <boost/units/conversion.hpp>
struct LengthBaseDimension : boost::units::base_dimension<LengthBaseDimension,1>{};
typedef LengthBaseDimension::dimension_type LengthDimension;
struct MeterBaseUnit : boost::units::base_unit<MeterBaseUnit, LengthDimension, 1>{};
template <> struct boost::units::base_unit_info<MeterBaseUnit>
{
static std::string name() { return "meter"; }
static std::string symbol() { return "m"; }
};
struct KilometerBaseUnit : boost::units::base_unit<KilometerBaseUnit, LengthDimension, 2>{};
template <> struct boost::units::base_unit_info<KilometerBaseUnit>
{
static std::string name() { return "kilometer"; }
static std::string symbol() { return "km"; }
};
// I don't want to use scaled_unit because I need this for my real purpose
BOOST_UNITS_DEFINE_CONVERSION_FACTOR(KilometerBaseUnit, MeterBaseUnit, double, 1000.0);
#endif
然后,我创建的文件,在其中units.h我定义自己的单元系统
#ifndef LIB_UNITS_H_
#define LIB_UNITS_H_
#include "length.h"
#include <boost/units/unit.hpp>
#include <boost/units/static_constant.hpp>
#include <boost/units/make_system.hpp>
#include <boost/units/io.hpp>
typedef boost::units::make_system<MeterBaseUnit>::type UnitsSystem;
typedef boost::units::unit<boost::units::dimensionless_type, UnitsSystem> Dimensionless;
typedef boost::units::unit<LengthDimension , UnitsSystem> SystemLength;
BOOST_UNITS_STATIC_CONSTANT(Kilometer , SystemLength);
BOOST_UNITS_STATIC_CONSTANT(Kilometers , SystemLength);
BOOST_UNITS_STATIC_CONSTANT(Meter , SystemLength);
BOOST_UNITS_STATIC_CONSTANT(Meters , SystemLength);
// Typedefs of dimensions
typedef boost::units::quantity<SystemLength> Length;
#endif
至少,我用这个头在我的主要功能
#include "units.h"
#include <iostream>
int main(void)
{
Length xLength1 (300.0 * Meters);
Length xLength2 (1500.0 * Kilometer);
Length xLength3;
std::cout << xLength2 << std::endl;
xLength3 = xLength1 + xLength2;
return 0;
}
该项目的编译,但它不会做我想做的。当我打印变量xLength2时,获得1500 m而不是1500 km或1500000 m。总和也是错误的,因为我忽略了1800米。这就像我认为公里为米,转换不起作用。
我在做什么错了?
你定义'千米'与'米'相同。我不记得什么是定义'公里数'(可能有不同的宏)'的首选方法,但你可以尝试像'const Length Kilometer = 1000 * Meters'(混洗定义顺序)。 – 2012-07-19 11:41:54
但是在这种情况下,我不能以公里为单位写出价值,只能以米为单位。我希望有可能与两个单位合作,并在需要的地方使用两个值。 – Jepessen 2012-07-19 17:16:36
如果你正在使用MSVC++或gcc,你可以用每个头顶部的#pragma once替换你的'#IFDEF LENGTH_H_'等警卫。 – 2012-08-09 13:57:11