Gri*_*fin 0 c++ time constructor stopwatch
嘿,所以我正在使用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;};
};
Run Code Online (Sandbox Code Playgroud)
这里是主要的()
int main()
{
Stopwatch myStopwatch(3,"start");
for(;;)
{
myStopwatch.Wait(2);
cout << myStopwatch.ElapsedTime() << endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么精度不能保持在我在构造函数中设置的值?谢谢!=) 哦,欢迎任何其他反馈我的代码!(我很新)
Stopwatch::Stopwatch(aDecNumb);
Run Code Online (Sandbox Code Playgroud)
这不会调用其他构造函数; 它甚至不是有效的C++.
您不能从另一个构造函数中为同一个对象调用一个构造函数.在创建对象期间只调用一个构造函数(当然不包括基类或成员构造函数).
但是,你并不需要两个构造函数; 一个就足够了:
Stopwatch(int DecNumb, char* command = 0) {
accuracy = 1;
for(; DecNumb > 0; DecNumb--) {
accuracy = accuracy * 10;
}
if (command && std::string(command) == "start") {
Start();
}
}
Run Code Online (Sandbox Code Playgroud)
如果你真的需要两个构造函数,最好的办法是使用一个执行多个构造函数通用的初始化的基类,或者使用可以从多个构造函数调用的"初始化"成员函数.
归档时间: |
|
查看次数: |
209 次 |
最近记录: |