【发布时间】:2017-09-28 15:45:45
【问题描述】:
我在尝试超载 operator float() 和 operator float() const 时遇到了问题。我以为我可以使用这两种重载来为“做事”和“只是阅读”提供不同的版本......但事实证明,对于包含这些重载的类的静态实例,我不能。
将问题归结为以下内容:
// Does some math and should convert to float
struct ToFloat
{
// float conversion here
operator float()
{
cout << "called operator float() of " << s << "\n";
f += 1.0f;
return f;
}
// just get current value here
operator float() const
{
cout << "called operator float() *const* of " << s << "\n";
return f;
}
float f;
std::string s;
};
// Uses a static and a normal member of ToFloat
struct Container
{
// return both instances (with some more math before)
operator float()
{
return s * m;
}
// just provide read access
operator float() const
{
return s * m;
}
static inline ToFloat s { 1.0f, "static" };
ToFloat m { 1.0f, "member" };
};
// Uses the container, but must also provide read-only access
struct Use
{
// Give me operator float() of my container
float get()
{
return c;
}
// Give me operator float() const of my container
float getC() const
{
return c;
}
Container c {};
};
int main()
{
Use u {};
printf("getC() %f \n\n", u.getC());
printf("get() %f \n\n", u.get());
printf("getC() %f \n\n", u.getC());
}
这会产生以下输出...
called operator float() of static
called operator float() *const* of member
getC() 2.000000
called operator float() of static
called operator float() of member
get() 6.000000
called operator float() of static
called operator float() *const* of member
getC() 8.000000
我真的不明白为什么ToFloat 的静态实例总是使用非const 转换,即使是从声明为const 的函数调用?这里适用什么规则?
【问题讨论】:
-
静态成员不是
const,只是因为类的一个实例是const。从该实例的代码中,它也不会出现为const。不相关,但使用float而不是默认的double通常只是发出愚蠢警告的邀请,维护人员会浪费时间试图弄清楚你为什么要这样做。 -
我的目标平台不支持双硬件。
-
@Cheersandhth.-Alf 关于
float与double:真的吗?我想说的是,在大量的数字运算代码中,很多人都在思考double的精度在哪里值得速度和内存成本。 -
@Angew:确实,有时
float很有用:它在语言中是有原因的。当你有无数个值时,它是空间的一半,当你或多或少地按顺序处理它们时,这也是你的速度。但一般默认float不太方便,有时比double慢,而且通常没有优势。 OP 的代码中没有任何内容表明float的合理用例。但是,他解释说这是由于硬件限制。
标签: c++ static type-conversion constants