C++变量作用域问题
我无法理解为什么会这样:
#include <iostream>
using namespace std;
int main(){
signed long int count = 1;
//...
count++;
return 0;
}
但是,如果我将标识符声明(限制)移动到脚本的开头(就在 using 命名空间之后),它无法编译并出现错误“count undeclared (first use in this function)” )" - 突出显示“count++;”行。
或者,Codepad 会导致以下错误:
In function 'int main()':
Line 16: error: reference to 'count' is ambiguous
compilation terminated due to -Wfatal-errors.
谢谢,
Will。
I can't understand why this works:
#include <iostream>
using namespace std;
int main(){
signed long int count = 1;
//...
count++;
return 0;
}
And yet if I move the identifier declaration (limit) to the start of the script (just after the using namespace), it fails to compile with the error "count undeclared (first use in this function)" - highlighting the line 'count++;'.
Alternatively, Codepad results in the following error:
In function 'int main()':
Line 16: error: reference to 'count' is ambiguous
compilation terminated due to -Wfatal-errors.
Thanks,
Will.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的
count
变量和std::count
之间可能存在冲突。您不应该使用
using namespace std
因为这会将标准库中的所有内容放入全局命名空间中,并且名称很快就会发生冲突。请改用特定的 using 行,例如
using std::cin;
。You probably have a collision between your
count
variable andstd::count
.You should not use
using namespace std
as this places everything from the standard library into the global namespace and names will soon collide.Use specific using lines such as
using std::cin;
instead.尝试使用 ::limit、::count 或 ::curNum
这表示它们是全局声明的。尽管如此,您应该避免全局声明任何变量,而是通过引用传递。
Try using ::limit, ::count, or ::curNum
This says they are declared globally. Although, you should avoid declaring any variables globally and pass by reference instead.
这对我来说编译和运行得很好:
This compiled and ran just fine for me: