可能重复:
C++: Easiest way to access main variable from function?C++我应该做什么,而不是全局变量?
我需要从我的主要功能让我的变量 “输入”,在a.cpp在b.cpp另一个名为检查功能。我在Google和这个论坛上看过它,我发现你可以使用extern
这个全局变量来做到这一点,但是这也是不好的,我无法找到一个替代方案的答案。我应该如何在不使用全局变量的情况下将变量中的数据传递给其他函数?
我如何获得参数的代码工作。 (我想在这里做的是一个控制台“经理”,我可以通过输入解决/查看项目欧拉的解决方案,我在40分钟前开始编码)
main.cpp
#include <iostream>
#include <windows.h>
#include "prob.h"
using namespace std;
int check(string x);
int main()
{
string input = "empty";
clear();
cout << "Welcome to the Apeture Labs Project Euler Console! (ALPEC)" << endl << endl;
cout << "We remind you that ALPEC will never threaten to stab you" << endl;
cout << "and, in fact, cannot speak. In the event that ALPEC does speak, " << endl;
cout << "we urge you to disregard its advice." << endl << endl;
cin >> input;
cin.get();
check(input);
cout << input << endl;
cin.get();
return 0;
}
prob.h
#ifndef PROB_H_INCLUDED
#define PROB_H_INCLUDED
int main();
int clear();
int check();
int back();
int P1();
int P2();
int P3();
int P4();
#endif // PROB_H_INCLUDED
back.cpp
#include <iostream>
#include <windows.h>
#include "prob.h"
using namespace std;
int clear()
{
system("@echo off");
system("color 09");
system("cls");
return 0;
}
int check(string x)
{
if(x == "help");
if(x == "empty")
{
cout << "And.... You didn't enter anything..." << endl << endl;
}
else
{
cout << "Do you have any clue what you are doing? " << endl << endl;
}
return 0;
}
函数参数。了解更多。 –
通过“这个论坛/ thingy”,你的意思是Stackoverflow?如果是这样,你看了什么问题。有这些:http://stackoverflow.com/questions/9668985/c-easiest-way-to-access-main-variable-from-function,http://stackoverflow.com/questions/11783435/how-to- access-variables-defined-and-declared-in-one-function-in-another-function,http://stackoverflow.com/questions/13594515/c-pass-variable-from-function-outside-main-into- function-call-inside-main,http://stackoverflow.com/questions/2139224/how-to-pass-objects-to-functions-in-c。你的似乎是第一个的复制品。 – jogojapan
这是另一个密切相关的一个:http://stackoverflow.com/questions/6371382/getting-access-to-another-functions-variables – jogojapan