该程序应该存储自午夜以来的秒数,并以标准和通用时间显示.它运行,但设置的Time函数中有一个错误,因为时间永远不会改变.我假设某些东西没有正确返回,但我找不到错误.
头文件:
#ifndef TIME_H #define TIME_H class Time { public: Time(); //constructor void setTime(int, int, int ); void printUniversal(); //print time in universal-time format void printStandard(); // print time in standard-time format private: int secondsSinceMidnight; }; #endif
.cpp文件
Time::Time()//constructor { secondsSinceMidnight = 0; } void Time::setTime(int h, int m, int s) { if ((h >= 0 && h < 24) && (m >= 0 && m < 60) && (s >= 0) && (s < 60)) { int hoursInSecs = (h * 3600); int minutesInSecs = (m * 60); secondsSinceMidnight = (minutesInSecs + hoursInSecs); } else throw invalid_argument( "hour, minute and/or second was out of range"); } void Time::printUniversal() { int secondsSinceMidnight = 0; int hours = (secondsSinceMidnight / 3600); int remainder = (secondsSinceMidnight % 3600); int minutes = (remainder / 60); int seconds = (remainder % 60); cout <主程序:
int main() { Time t; //instantiate object t of class Time //output Time object t's initial values cout<<"The initial universal time is "; t.printUniversal(); cout<<"\nThe initial standard time is "; t.printStandard(); int h; int m; int s; cout<<"\nEnter the hours, minutes and seconds to reset the time: "<>h>>m>>s; t.setTime(h, m, s); //change time //output Time object t's new values cout<<"\n\nUniversal time after setTime is "; t.printUniversal(); cout<<"\nStandard time after setTime is "; t.printStandard(); }
Tim Seguine.. 5
在您的打印功能中,您有一个与您的字段同名的本地变量
secondsSinceMidnight
.它正在遮蔽它.