更改main中变量的值以用于其他函数(C++)
在C++中,要在其他函数中使用main函数中的变量,可以通过以下方法实现:
#include<iostream>
int myVar;
void otherFunction() {
std::cout << "myVar in otherFunction: " << myVar<< std::endl;
}
int main() {
myVar = 10;
std::cout << "myVar in main: " << myVar<< std::endl;
otherFunction();
return 0;
}
#include<iostream>
void otherFunction(int var) {
std::cout << "myVar in otherFunction: "<< var<< std::endl;
}
int main() {
int myVar = 10;
std::cout << "myVar in main: " << myVar<< std::endl;
otherFunction(myVar);
return 0;
}
#include<iostream>
void otherFunction(int* var) {
std::cout << "myVar in otherFunction: " << *var<< std::endl;
*var = 20;
}
int main() {
int myVar = 10;
std::cout << "myVar in main: " << myVar<< std::endl;
otherFunction(&myVar);
std::cout << "myVar in main after otherFunction: " << myVar<< std::endl;
return 0;
}
#include<iostream>
void otherFunction(int& var) {
std::cout << "myVar in otherFunction: "<< var<< std::endl;
var = 20;
}
int main() {
int myVar = 10;
std::cout << "myVar in main: " << myVar<< std::endl;
otherFunction(myVar);
std::cout << "myVar in main after otherFunction: " << myVar<< std::endl;
return 0;
}
以上是四种在C++中将main函数中的变量传递给其他函数的方法。
领取专属 10元无门槛券
手把手带您无忧上云