如何将模数与全局变量和命名空间std一起使用? [关闭]

问题描述 投票:-3回答:2

是的我知道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 stdremainder保持为全局变量?

#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;
}
c++ modulus
2个回答
4
投票

问题是您的全局变量名称与标准库中的std::remainder冲突。 Example on Compiler Explorer

using namespace std;的问题在于它将如此多的符号带入全局命名空间,这种错误几乎是不可避免的。除了最简单的玩具程序之外,这是一个不好的做法。


3
投票

冲突是与std::remainder,而不是与%。您选择的变量名与std名称空间中的函数冲突。你已经知道using namespace std;很糟糕,所以我会饶了你。

选项:

  1. 丢失using声明。
  2. 重命名remainder变量。
  3. remainder变量放在它自己的命名空间中,并通过该命名空间显式引用它。
© www.soinside.com 2019 - 2024. All rights reserved.