我在我的计算机上使用 Xcode for C++,同时在学校使用 Visual Studio。 下面的代码在 Visual Studio 中工作得很好,但我在使用 Xcode 时遇到了这个问题。
clock c1(2, 3, 30);
一切正常,但它一直给我这个错误,提示“Expected ';'在 'c1' 之前”
好吧,我把';' .. 但是,它给了我这个错误:“'c1' 未在此范围内声明”
这是整个标题代码:
#include <iostream>
using namespace std;
class clock
{
private:
int h;
int m;
int s;
public:
clock(int hr, int mn, int sec);
};
clock::clock(int hr, int mn, int sec)
{
h = hr;
m = mn;
s = sec;
}
这是完整的 .cpp 代码:
#include "clock.h"
int main()
{
clock c1(2, 3, 30);
return 0;
}
我将所有内容都剥离到我遇到问题的地方。据我所知,其他一切都是无关紧要的,因为问题仍然与上述问题相同。
提前致谢!
最佳答案
有一个函数 clock
可以隐藏同名的 clock
类。你可以通过说来解决这个问题
class clock c1(2, 3, 30);
在 header 中使用 using namespace std;
是非常糟糕的做法。而是将该行仅放入 cpp
文件中。如果您删除该行(如果名称来自命名空间 std::
而不是最初来自全局命名空间),它可能会解决您的问题。
关于c++ - 未在范围内声明的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2402636/