错误:"T"之前应为";"

error: expected `;' before ‘T’

本文关键字:错误      更新时间:2023-10-16

我知道以前可能会问这个问题,但不幸的是,我无法调试错误。

我为时间写了一节课:

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类时间.cpp:在函数"int main()"中:

4-5类时间.cpp:8:错误:应为";"在"T"之前

4-5类时间.cpp:10:错误:未在此作用域中声明"T"

提前感谢您的帮助!

类的名称time似乎是一个保留字,不能使用。如果你把它改成mytime,就像我在这里做的那样,你会发现它的工作方式和预期的一样。

我必须找出为什么time是一个保留字,或者发生了什么。

显然,您的类名与全局::time结构冲突,这对于编译器为什么不接受它是有道理的。

如果您真的想使用time类,那么应该创建自己的名称空间并将其放入其中。

namespace tony { class time {}; } int main() { tony::time t; }这将消除名称冲突。

尝试将"class"文件从time.h/time.cpp重命名为mytime.h/mytime.cpp

有一个名为time.h的系统包含文件,根据为编译器配置的包含文件搜索顺序,系统文件可能优先于您的系统文件。因此编译器根本看不到您的Time类。

您在time.cpp的第22行有一个拼写错误:

<< " : " << (seconde < 10 ? "0" : "") << second

应为:

<< " : " << (second < 10 ? "0" : "") << second
#include <ctime>
namespace {
class time {};
}
int main()
{
    time();
}

给出错误:

main.cpp: In function 'int main()':
main.cpp:9:5: error: reference to 'time' is ambiguous
In file included from /usr/include/c++/4.7/ctime:44:0,
                 from main.cpp:1:
/usr/include/time.h:186:15: error: candidates are: time_t time(time_t*)
main.cpp:4:7: error:                 class {anonymous}::time

去掉匿名名称空间可以消除歧义。奇怪:

main.cpp: In function 'int main()':
main.cpp:7:10: error: too few arguments to function 'time_t time(time_t*)'
In file included from /usr/include/c++/4.7/ctime:44:0,
                 from main.cpp:1:
/usr/include/time.h:186:15: note: declared here