Timer working improperly
I have a problem with a timer class based on a SDL timer.
class CTimer
{
public:
CTimer(): startTick(0), endTick(0), curTime(0), running(false) {};
void Start() { startTick += SDL_GetTicks() - endTick; running = true; };
void Stop() { endTick = SDL_GetTicks(); running = false; };
void Reset() { startTick = 0; endTick = 0; curTime = 开发者_Go百科0; };
inline int operator()() { return running ? curTime = ((int) SDL_GetTicks - startTick) / 1000 + 1 : curTime; };
private:
int startTick;
int endTick;
int curTime;
bool running;
};
The () operator should return time in seconds (stored in curTime). But it always returns 4202 (curTime is always equal to that). What am I doing wrong?
Test code:
int main()
{
SDL_Init (SDL_INIT_TIMER);
CApp::CTimer timer;
timer.Start();
for (int i = 0; i < 15; ++i)
{
SDL_Delay (1000);
std::cout << timer() << '\n';
}
return 0;
}
This is a perfect example of why you don't want to use old-style C casts in C++.
(int) SDL_GetTicks
The missing parentheses on the function call mean you're casting a pointer to the function to an int, not the return value. Surprisingly enough the pointer to the function never changes.
Are you missing parentheses for SDL_GetTicks?
inline int operator()() { return running ? curTime = ((int) SDL_GetTicks - startTick) / 1000 + 1 : curTime; };
For starters,
inline int operator()() { return running ? curTime =
((int) SDL_GetTicks - startTick) / 1000 + 1 : curTime; };
should be
inline int operator()() { return running ? curTime =
((int) SDL_GetTicks() - startTick) / 1000 + 1 : curTime; };
I would think.
Did you get a warning error about this?
In addition to the attempted call to SDL_GetTicks
instead of SDL_GetTicks()
causing it to take the address of that function (and always returning the constant as you observed), it looks like if you call Start
and then Stop
before calling operator()
you won't get a meaningful result.
精彩评论