C++:如何在各种不同的函数中使用全局变量

C++: How can I used global variables in various different functions?

本文关键字:函数 全局变量 C++      更新时间:2023-10-16

有没有办法让全局变量(在本例中是向量)在任何函数中保留其内容?我正在试着看看我是否能做到这一点:

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()调用some_function()some_otherfunction():,您所显示的内容将正常工作

#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;
}

您发布的代码将实现您想要的目标。您有一个向量实例(collected_input),它用于多个函数。您的向量实际上是全局的,事实上,其他源文件也可以通过使用extern关键字声明同名向量来访问它,尽管强烈建议不要这样做。

当然,现在您的程序什么也不做,因为main()函数不包含任何代码。如果您从main()调用两个函数,然后打印矢量,您会发现这两个函数都成功地对矢量进行了操作。