C++:如何在各种不同的函数中使用全局变量?
有没有办法让一个全局变量在这种情况下,一个向量在所有函数中都保留它的内容?我想看看我是否能做到这一点:C++:如何在各种不同的函数中使用全局变量?,c++,variables,global,C++,Variables,Global,有没有办法让一个全局变量在这种情况下,一个向量在所有函数中都保留它的内容?我想看看我是否能做到这一点: vector<string> collected_input; //global void some_function{ string bla = "towel"; collected_input.push_back(bla); //collected_input gains "towel" } void some_otherfunction{ string xyz = "zy
vector<string> collected_input; //global
void some_function{
string bla = "towel";
collected_input.push_back(bla); //collected_input gains "towel"
}
void some_otherfunction{
string xyz = "zyx"
collected_input.push_back(xyz); //collected_input gains "zyx"
}
int main(){
// print the contents of the collected_input vector
}
如果main调用了一些函数和其他函数,那么您所展示的将很好地工作:
你发布的代码将实现你想要的。您有一个向量收集的_输入实例,可跨多个函数使用。您的向量实际上是全局的,事实上,其他源文件可以通过使用extern关键字声明同名向量来访问它,尽管强烈建议不要这样做
当然,现在您的程序什么都不做,因为您的主函数不包含任何代码。如果您从main调用两个函数,然后打印向量,您会发现这两个函数都在向量上成功运行。您遇到的实际问题是什么?编译器在main中告诉我,收集的输入未在该范围内声明。@RogerVillanueva那么您发布的代码不能代表您的问题,由于您的主函数为空,无法产生该错误。@RogerVillanueva:您可能在定义collected_input和main的上方某个地方缺少右括号。是否在一个源文件中定义了多个源文件和全局变量,然后需要在其他源文件中声明它
#include <ostream>
#include <vector>
#include <string>
using namespace std;
vector<string> collected_input;
void some_function()
{
string bla = "towel";
collected_input.push_back(bla);
}
void some_otherfunction()
{
string xyz = "zyx"
collected_input.push_back(xyz);
}
int main()
{
some_function();
some_otherfunction();
for (vector<string>::iterator iter = collected_input.begin();
iter != collected_input.end();
++iter)
{
cout << *iter << '\n';
}
return 0;
}