似乎无法在主目录中调用类

Can't seem to call a class in main

本文关键字:调用 主目录      更新时间:2023-10-16

我试图获取对我的类的引用,但似乎没有声明to

这意味着它是未声明的:

#include <iostream>
using namespace std;
class time
{
private:
    int sec;
    int mins;
    int hours;
public:
    void setSeconds(int x)
    {
        sec = x;
    }
    int getSeconds()
    {
        return sec;
    }
};
int main()
{
    time to;
    to.setSeconds(10000000);
    cout << to.getSeconds() << endl;
    return 0;
}

错误如下:

main.cpp: In function 'int main()':
main.cpp:29:10: error: expected ';' before 'to'
     time to;
          ^
main.cpp:29:12: warning: statement is a reference, not call, to function 'time' [-Waddress]
     time to;
            ^
main.cpp:29:12: warning: statement has no effect [-Wunused-value]
main.cpp:30:5: error: 'to' was not declared in this scope
     to.setSeconds(10000000);
     ^

std::time是C++标准库中的一个函数,由于您using namespace std,因此默认情况下使用它而不是您的类。

您甚至无法编写::time来引用您的,因为编译器的标准库实现恰好在将其包装到命名空间std之前也包含旧的 C ::time

使用以下部分或全部建议:

  • 给你的班级一个更好、更独特的名字
  • 编写class time来引用您的类(这可确保使用类型 time,但这是一个糟糕的黑客)
  • 自己使用命名空间以避免将来的所有歧义(建议这样做)

您还应该停止一般using namespace std以帮助避免尽可能多的麻烦,尽管在这种情况下它不能直接帮助您。

Clang 给出了更好的错误消息:

time.cpp:29:5: error: must use 'class' tag to refer to type 'time' in this scope
    time t;
    ^
    class 
/usr/include/time.h:192:15: note: class 'time' is hidden by a non-type declaration of 'time' here
extern time_t time (time_t *__timer) __THROW;
              ^

它与using namespace std无关。 相反,全局时间函数是冲突的。