将浮点向量转换为双精度

时间:2018-07-30 09:33:06

标签: c++ vector double

我对C ++相当陌生,所以请原谅我对此的无知。 我试图将双精度矢量转换为浮点矢量,以在某些情况下使用(我知道存在精度损失)。 向量的结构很简单,

struct Dvector
{
public:

double X;
double Y;
double Z;

是否创建了一个简单的函数,可以在多个区域中调用该函数,以将其转换为诸如float的结构?

   struct Fvector
{
public:

float X;
float Y;
float Z;

1 个答案:

答案 0 :(得分:0)

要将Fvector转换为Dvector,可以使用user-defined conversion。看下面的代码。

#include <iostream>

using namespace std;

struct Dvector
{
public:
    double X;
    double Y;
    double Z;
};

struct Fvector
{
public:
    float X;
    float Y;
    float Z;

    explicit operator Dvector()
    {
        Dvector d;
        d.X = static_cast<double>(X);
        d.Y = static_cast<double>(Y);
        d.Z = static_cast<double>(Z);

        return d;
    }
};

int main()
{
    Fvector f = {1.0f, 2.0f, 3.0f};
    Dvector d = static_cast<Dvector>(f);
    std::cout << d.X << d.Y << d.Z;
    return 0;
}