我知道之前可能会被问到这个问题,但不幸的是我无法调试错误。
我为了时间写了一个类:
class time
{
public:
time(); //constructor
void setTime (int, int, int); //set time
void dispTime(); //print time
private:
int hour, minute, second;
};
然后我实现函数成员:
#include <iostream>
#include "stdio.h"
#include "time.h"
time :: time()
{
hour = 12;
minute = 0;
second = 0;
}
//**********
void time::setTime(int h, int m, int s)
{
hour = (h >= 0 && h < 12) ? h : 0;
minute = (m >= 0 && m < 60) ? m : 0;
second = (s >= 0 && s < 60) ? s : 0;
}
//**********
void time::dispTime()
{
std::cout << ((hour == 0 || hour == 12) ? 12 : hour % 12)
<< " : " << (minute < 10 ? "0" : "") << minute
<< " : " << (second < 10 ? "0" : "") << second
<< (hour < 12 ? " AM" : " PM");
}
最后是正文主体:
#include <iostream>
#include "stdio.h"
#include "time.h"
using namespace std;
//**********
int main()
{
time T;
cout << "The initial standard time is: ";
T.dispTime();
T.setTime(13, 27, 36);
cout << "\nStandard time after set-time is: ";
T.dispTime();
T.setTime(99,83,12); //attemp to have a invalid time
cout << "\nStandard time is invalid and standard time is: ";
T.dispTime();
cin.get();
cin.get();
}
当我用 g++ 编译它时:
4-5-class-time.cpp: 在函数“int main()”中:
4-5-class-time.cpp:8: 错误:应为 `;'在'T'之前
4-5-class-time.cpp:10: 错误:“T”未在此范围内声明
预先感谢您的帮助!
最佳答案
看起来你的类名 time
是一个保留字,不能使用。如果你把它改成mytime
,就像我做的那样here ,您会发现它按预期工作。
我将不得不找出为什么 time
是一个保留字或发生了什么。
显然您的类名与全局 ::time
结构冲突,这对于编译器不接受它的原因是有道理的。
如果您真的想使用 time
类,您应该创建自己的命名空间并将其放在那里。
namespace tony { class time {}; } int main() { tony::time t;
这应该会消除名称冲突。
关于c++ - 错误 : expected `;' before ‘T’ ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14976452/