c++ - 错误: expected ';' before defining object of class

标签 c++

#include <iostream>
using namespace std;

class time
{
    private:
        int hour;
        int min;
        int sec;
    public:
        void get_time(int h,int m,int s)
        {
            hour = h;
            min = m;
            sec = s;
        }
        void show_time()
        {
            cout << "The time is: " << hour << "hours " << min << "minutes " << sec << "seconds";
        }
};

int main()
{
    time t1;
    t1.get_time(5, 4, 2);
    t1.show_time();
    return 0;
}

output:
    time.cpp: In function ‘int main()’:
    time.cpp:25:7: error: expected ‘;’ before ‘t1’
      time t1;
           ^
    time.cpp:28:2: error: ‘t1’ was not declared in this scope
      t1.get_time(5, 4, 2);
      ^

最佳答案

有一个名为 time 的全局函数,继承自C标准库。它隐藏了您的类名称,[basic.scope.declarative]/4:

Given a set of declarations in a single declarative region, each of which specifies the same unqualified name,

  • [..]

  • exactly one declaration shall declare a class name or enumeration name that is not a typedef name and the other declarations shall [..] all refer to functions and function templates; in this case the class name or enumeration name is hidden (3.3.10). [..]

最简单的解决方案是为您的类指定另一个名称(例如 Time - C 和 C++ 标准库从不在标识符中使用大写字母)。

关于c++ - 错误: expected ';' before defining object of class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28135075/

相关文章:

c++ - "Overloading"模板化和非模板化类型

c++ - 指针如何引用不同的类型?

c++ - 了解 OpenCV fitEllipse 方法

c++ - 不明白用双指针创建二维动态数组(**)

c++ - Find optimal route in farm land-dynamic programming/Dijkstra的

c++ - eclipse CDT : 'can' t find a source file' while debugging

c++ - QHash 问题

c++ - C 与模块系统

c++ - Windows 10 是否会防止您访问其他程序正在使用的内存?

c++ - Uncrustify 代码格式化程序删除了 C++ 单行代码中的空格