C++:如何在各种不同的函数中使用全局变量
C++: How can I used global variables in various different functions?
有没有办法让全局变量(在本例中是向量)在任何函数中保留其内容?我正在试着看看我是否能做到这一点:
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()调用两个函数,然后打印矢量,您会发现这两个函数都成功地对矢量进行了操作。
相关文章:
- 内联函数中具有内部链接的全局变量
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- C++ 在编译时具有函数计算全局变量
- 修改程序的入口点时未调用全局变量的构造函数
- 赋予全局变量而不是局部变量优先级的函数 - (异常行为)
- std::线程不是全局变量,但在到达创建它的函数的末尾时不会超出范围?
- 如何在全局变量的构造函数之前运行函数
- 如何获取使用全局变量的所有函数名称?
- 在 C++17 中修改 constexpr 函数中的全局变量
- C++从 std::async 函数读取命名空间中的全局变量标志
- 为什么我的类函数不使用我的全局变量?
- 有什么理由C++ 11+ std::mutex 应该声明为全局变量,而不是作为函数参数传递到 std::thread 中
- 将全局变量的名称作为输入并更改其值的函数
- 如何使用 c++ 中的函数访问全局变量?
- 是否可以通过全局变量定义具有可变参数数的函数中的参数数量
- 如何创建用于多个源文件的全局变量/包含/函数
- 查找全局变量,而不是在 c++ 函数中构造它们
- 通过使用全局变量的函数访问在给定范围内被覆盖的变量
- 具有递归函数且不带全局变量的程序 - C++
- C++:如何从静态函数写入全局变量