C ++同样的变量作为int和float [英] C++ same variable act as int and float

查看:211
本文介绍了C ++同样的变量作为int和float的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有情况,我需要保持值float以及int。所以尝试像下面。但没有帮助。可以帮助任何人吗?

I have on situation, where i need to keep the value float as well as int. so tried like below. but no help. can any one help on this?

union Val {
        int a;
        float b;
    };

    Val p;
    p.b = 45.56;

    int k = p.a; // i want k should be 45;


推荐答案

我看到您说


我不想每次将它从float转换为int [sic]

i dont want each time it to be converted from float to int [sic]

可以使用用户定义的转化来完成此操作。

To do that you could use user-defined conversions to accomplish this.

所以你的结构如下:

class Val {
    int a;
    float b;
public:
    Val& operator= (const int _a) {a = _a; b = _a + fmod(b, 1.0F); return *this;}
    Val& operator= (const float _b) {b = _b; a = trunc(_b); return *this;}
    operator int() {return a;}
    operator float() {return b;}
};

请注意,你真正想要使用的只是一个 float static_cast< int> 对于 static_cast

Please note that what you really want to use is simply a float with static_cast<int> For astatic_cast:


以确保正在转换的对象实际上是目标类型的完整对象。因此,由程序员确保转换是安全的。另一方面,它不会产生 dynamic_cast 的类型安全检查的开销。

No checks are performed during runtime to guarantee that the object being converted is in fact a full object of the destination type. Therefore, it is up to the programmer to ensure that the conversion is safe. On the other side, it does not incur the overhead of the type-safety checks of dynamic_cast.

我在这里提供了使用 Val 的示例: http://ideone.com/XUesib ,但您可以完成与 float foo 完全相同的事情:

I've provided an example of using Val here: http://ideone.com/XUesib but you could accomplish the exact same thing given float foo like this:

foo = 1.3F;
cout << static_cast<int>(foo) << endl << foo << endl;
foo = 13 + fmod(foo, 1.0F);
cout << static_cast<int>(foo) << endl << foo << endl;

这篇关于C ++同样的变量作为int和float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆