c++ - 似乎无法在 main 中调用一个类

标签 c++

我正在尝试获取对我的类的引用,但似乎未声明 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++ 标准库中的一个函数,并且由于您正在使用命名空间 std,因此默认使用它而不是您的类。

你甚至不能编写 ::time 来引用你的,因为你的编译器的标准库实现恰好在包装它之前也包含了旧的 C ::time进入命名空间 std

使用这些建议中的部分或全部:

  • 给你的类(class)取一个更好、更独特的名字
  • 编写 class time 以引用您的类(class)( this ensures the type time is used ,但这是一个糟糕的 hack)
  • 自己使用命名空间以避免所有 future 的歧义(推荐)

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

关于c++ - 似乎无法在 main 中调用一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27389838/

相关文章:

c++ - constexpr如何推导值?

c++ - STL vector 中值的索引范围的算法

c++ - 有什么理由使用 switch 语句而不是 if 和 elseif 字符串吗?

c++ - 两个 for 嵌套循环的区别。(C++)

c++ - Google 的 Native Client 和编译 SDL2

c++ - 确保给定图像与另一图像翻转

c++ - 我无法弄清楚我用Kruskal算法实现MST出了什么问题

c++ - Halide 中的 Cholesky 分解

c++ - 编写一个程序,提示用户输入五个十进制数

c++ - 从数据中创建/放置圆圈/网格的简单数据可视化