如何将模数与全局变量和命名空间标准一起使用?
How to use modulus with a global variable and namespace std?
是的,我知道 using namespace std
是一种不好的做法,但我已经编写了大部分代码,其中包含此声明,我认为我没有时间回去修改它。
全局变量的原因是我正在使用需要访问该变量并需要修改它的多个线程。
我的问题是,我全局声明了 int remainder = 0;
,例如在我的主线程中我调用了 remainder = 13 % 5;
。
这给了我一个错误 'int remainder' redeclared as a different kind of symbol
并且我读到原因是 using namespace std
覆盖了 std::modulus
运算符,如果我理解正确的话。
我可以使用哪些其他方法来执行此功能,将 using namespace std
和 remainder
保留为全局变量?
#include<iostream>
#include<cmath>
using namespace std;
int remainder = 0;
void testing();
int main(){
testing();
cout << remainder << endl;
return 0;
}
void testing(){
remainder = 13 % 5;
}
问题是你的全局变量名与std::remainder
from the standard library. Example on Compiler Explorer冲突。
using namespace std;
的问题是它将太多的符号带入了全局命名空间,这个错误几乎是不可避免的。除了最简单的玩具程序,这对任何东西都是不好的做法。
冲突发生在 std::remainder
,而不是 %
。您选择的变量名称与 std
命名空间中的函数冲突。你已经知道using namespace std;
不好了,所以我会饶过你。
选项:
丢掉using
语句。
重命名 remainder
变量。
将remainder
变量放在它自己的命名空间中,并通过该命名空间显式引用它。
是的,我知道 using namespace std
是一种不好的做法,但我已经编写了大部分代码,其中包含此声明,我认为我没有时间回去修改它。
全局变量的原因是我正在使用需要访问该变量并需要修改它的多个线程。
我的问题是,我全局声明了 int remainder = 0;
,例如在我的主线程中我调用了 remainder = 13 % 5;
。
这给了我一个错误 'int remainder' redeclared as a different kind of symbol
并且我读到原因是 using namespace std
覆盖了 std::modulus
运算符,如果我理解正确的话。
我可以使用哪些其他方法来执行此功能,将 using namespace std
和 remainder
保留为全局变量?
#include<iostream>
#include<cmath>
using namespace std;
int remainder = 0;
void testing();
int main(){
testing();
cout << remainder << endl;
return 0;
}
void testing(){
remainder = 13 % 5;
}
问题是你的全局变量名与std::remainder
from the standard library. Example on Compiler Explorer冲突。
using namespace std;
的问题是它将太多的符号带入了全局命名空间,这个错误几乎是不可避免的。除了最简单的玩具程序,这对任何东西都是不好的做法。
冲突发生在 std::remainder
,而不是 %
。您选择的变量名称与 std
命名空间中的函数冲突。你已经知道using namespace std;
不好了,所以我会饶过你。
选项:
丢掉
using
语句。重命名
remainder
变量。将
remainder
变量放在它自己的命名空间中,并通过该命名空间显式引用它。