可能重複:
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