开发者

Using static class data in std::max and min

I have a static class data member declared as:

static const float MINIMUM_ZOOM_FACTOR = 4.0;

I'm using this constant in a开发者_StackOverflow class member function like this:

zoomFactor_ = max(zoomFactor_, MINIMUM_ZOOM_FACTOR);

At this point, the compiler complains that MINIMUM_ZOOM_FACTOR is an undefined reference. However if I use it directly like this:

if(fabs(zoomFactor_ - MINIMUM_ZOOM_FACTOR) < EPSILON) ...

it works a-ok. What am I doing wrong?


Only integer constants can be defined inside the class like that. Floating point (or class type) constants must be declared in the class, and then defined and initialised once outside. In practice, that means you must define it in a source file.

// header file
class thingy
{
    static const float MAXIMUM_ZOOM_FACTOR;
};

// source file
const float thingy::MAXIMUM_ZOOM_FACTOR = 4.0f;

As to why direct use works but max doesn't: max takes its arguments by reference, so it may require the address of the constant object. If you haven't defined the object then that won't work. Direct use might substitute it for a compile-time constant, which doesn't require an address.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜