c++ - 错误 : expected `;' before ‘T’

标签 c++ class

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

我为了时间写了一个类:

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/

相关文章:

C++ const 引用 vector(或其他动态容器)中的类变量

c++ - 使用 C++ 获取核心的独占所有权并禁用其中断

c++ - 'override' 限定符与尾随返回类型一起去哪里?

Java 泛型 - 如果调用的方法中不存在类的泛型类型,为什么会出现 "incompatible types"编译错误?

c++ - 非静态数据成员 c++ 的无效使用

c++ - 读取悖论时间戳字段

c++ - 预期的说明符限定符列表之前... C++/Objective-C iPhone 项目中的错误

javascript - 如何扩展javascript类

C++,头文件中的对象声明

ios - 一个类继承另一个类并遵守一个协议(protocol)——试图调和两个​​接口(interface)