Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/141.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何跨多个函数使用变量?_C++_Function_Variables_Parameter Passing_User Defined Functions - Fatal编程技术网

C++ 如何跨多个函数使用变量?

C++ 如何跨多个函数使用变量?,c++,function,variables,parameter-passing,user-defined-functions,C++,Function,Variables,Parameter Passing,User Defined Functions,假设我有一个简单的控制台程序,如下所示: (我还没有测试过,可能会有错误,因为我是个新手) #包括 使用名称空间std; void startProgram(); int main(){ a=20;//我想以某种方式设置它,以便在任何其他函数中使用它 //没有像启动程序(a)那样通过它; startProgram(); 返回0; } void startProgram(){ cout实际上只有两种方法:全局变量或参数传递 如果将变量声明为全局变量,即在全局范围之外(和之前)任何函数,然后所有函数

假设我有一个简单的控制台程序,如下所示:

(我还没有测试过,可能会有错误,因为我是个新手)

#包括
使用名称空间std;
void startProgram();
int main(){
a=20;//我想以某种方式设置它,以便在任何其他函数中使用它
//没有像启动程序(a)那样通过它;
startProgram();
返回0;
}
void startProgram(){

cout实际上只有两种方法:全局变量或参数传递

如果将变量声明为全局变量,即在全局范围之外(和之前)任何函数,然后所有函数都可以使用它。但是,全局变量应尽可能少地使用。相反,我建议您将其作为参数传递,如果以后其他函数需要使用该变量,则继续将其作为参数传递


或者,当然,既然你使用C++,为什么不定义一个类并使变量成为类的成员?然后你可以把所有相关函数放在这个类中,并且所有的变量都可以使用它而不使它成为全局的或作为参数传递它。

使它成为全局的。但是为什么不想通过它呢?这是最好的方法。案例。因为我必须传递和返回大量的变量,因为我将尝试在比上面示例更大的范围内使用它。欢迎使用编程。如果变量太多,请将相关的变量放入结构或类似结构中。规模越大,你越有可能踩到全局变量并使用副作用。
#include <iostream>
using namespace std;
void startProgram();

int main(){
a = 20; //I want to somehow set this so that I can use it in any other function
//without passing it through like startProgram(a);

startProgram();
return 0;
}

void startProgram(){
cout << a << endl;
}