我正在尝试获取对我的类的引用,但似乎未声明 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 typetime
is used ,但这是一个糟糕的 hack) - 自己使用命名空间以避免所有 future 的歧义(推荐)
一般情况下,您还应该停止using namespace std
以帮助避免尽可能多的麻烦,尽管在这种情况下它不能直接帮助您。
关于c++ - 似乎无法在 main 中调用一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27389838/