我在尝试超载operator float()
和operator float() const
时遇到了一个问题。我以为我可以使用两个过载来为"做事"one_answers"读"提供不同的版本...但是事实证明,在类静态实例的情况下,包含这些超载的静态实例。
将问题归结为几乎减少了:
// 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 nn", u.getC());
printf("get() %f nn", u.get());
printf("getC() %f nn", 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
的函数中调用?什么规则在这里适用?
静态数据成员Container::s
仅为ToFloat
类型。它始终直接通过this
的隐式解除直接访问。换句话说,容器的const
操作员实际上是这样:
operator float() const
{
return Container::s * this->m;
}
由此,显然没有理由将Container::s
视为const
,仅仅是因为this
是const Container *
。如果您希望将其视为const
,则必须明确符合资格:
operator float() const
{
return std::as_const(s) * m;
}