【发布时间】:2011-08-23 20:38:20
【问题描述】:
嘿,所以我正在使用 windows GetTickCount() 和 STL 处理秒表类,但是在将 Stopwatch(int DecNumb) 构造函数实现到重载 Stopwatch(int DecNumb, char command[ ]) 在后一个构造函数中未正确设置“准确性”数据类型。
(好像又恢复到以前的unsigned long int 560345什么的值了……)
这是我用来测试它的 class 和 main() 命令:
class Stopwatch
{
protected:
int accuracy;
unsigned long int initial_ilu;
unsigned long int current_ilu;
long float output_fl;
vector<long float> times;
public:
Stopwatch(int DecNumb) { // so accuracy*10 isn't 0
accuracy = 1;
for(;DecNumb>0;DecNumb--) // the Tick count will
accuracy = accuracy*10;}; // diveded by accuracy (each 0 in this number moves the decimal over once)
Stopwatch(int aDecNumb, char command[]) {Stopwatch::Stopwatch(aDecNumb);
if(command = "start") Stopwatch::Start();};
void Start(){initial_ilu = GetTickCount()/*/accuracy*/;};
long float ElapsedTime()
{
current_ilu = GetTickCount()/*/accuracy*/;
output_fl = (current_ilu - initial_ilu)/accuracy;
return output_fl;
};
void Wait(long float seconds)
{
for(unsigned long int waitTime = GetTickCount() + (seconds*accuracy);
waitTime > GetTickCount();) {}
// stay stuck in for loop until time specified is up
};
void SaveTime(){times.push_back(GetTickCount()/*/accuracy*/);};
long float GetTime(int location){if(times.size()<location+1) return times[location+1];
else return -1;};
};
这里是 main()
int main()
{
Stopwatch myStopwatch(3,"start");
for(;;)
{
myStopwatch.Wait(2);
cout << myStopwatch.ElapsedTime() << endl;
}
return 0;
}
为什么精度不能保持在我在构造函数中设置的值? 谢谢! =) 哦,欢迎对我的代码提供任何其他反馈! (我比较新)
【问题讨论】:
-
为什么要长时间浮动?你的意思是双倍的?受保护的数据通常是一件坏事。
-
既然您要求其他反馈,除非代码对性能至关重要或需要与遗留代码互操作,否则确实没有理由使用 C 字符串。最好尽可能使用
std::string(或其他字符串类,如果您使用的是其他框架),例如,用于构造函数的command参数。 -
我猜应该是
if (command == "start")而不是if (command = "start")。请注意,这只是指针比较,不是内容比较。 -
你确实可以调用另一个构造函数,但不能不使用临时:
*this = StopWatch(aDecNumb);应该可以工作 -
StopWatch::Wait()是一个繁忙的循环,会疯狂地消耗 CPU 周期,直到时间过去。请考虑暂停当前进程的其他等待机制。
标签: c++ time constructor stopwatch