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

时间:2014-11-11 02:49:44

标签: 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 = "zyx"
collected_input.push_back(xyz); //collected_input gains "zyx"
}

int main(){
// print the contents of the collected_input vector
}

2 个答案:

答案 0 :(得分:1)

如果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;
}

答案 1 :(得分:0)

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

当然,现在你的程序什么都不做,因为你的main()函数不包含任何代码。如果你从main()调用两个函数然后打印向量,你会发现这两个函数在向量上成功运行。

相关问题