[英]Access static variables inside functions from main() without classes in C++
這是我使用C ++的面向對象編程類的一項工作。 在此程序中,我需要能夠從另一個函數訪問在一個函數中初始化的靜態指針。 更具體地說,我希望能夠從“輸入”功能訪問在“分配”功能中初始化的指針x。 而且在任何人問之前,我都不允許使用任何全局變量。
#include <iostream>
using namespace std;
void allocation()
{
static int *pointerArray[3];
static int **x = &pointerArray[0];
}
bool numberCheck(int i)
{
if(i >= 0)
{
return true;
}
else
{
return false;
}
}
void input()
{
int input1,input2;
cout << "Input two non-negative integers.\n";
cin >> input1;
while(!numberCheck(input1))
{
cout << "You typed a non-negative integer. Please try again.\n";
cin >> input1;
}
cin >> input2;
while(!numberCheck(input2))
{
cout << "You typed a non-negative integer. Please try again\n";
cin >> input2;
}
// Here I'd like to access pointer x from the allocation function
}
int main()
{
allocation();
input();
return 0;
}
如果沒有allocation
功能本身的合作,就無法以可移植的方式完成此任務。
范圍規則可防止在實際allocation
函數之外使用x
。 它的持續時間可能在函數之外(是靜態的),但它的范圍(即,其可見性)不在函數的范圍內。
有可能是黑客 ,你可以在一些實現使用,但是,如果你要學習的語言,你最好學會正確的,而不是依賴,不會到處工作技巧的語言。
如果您被允許以某種方式更改 allocation
函數,我將調查以下內容:
void allocation (int ***px) {
static int *pointerArray[3];
static int **x = &pointerArray[0];
*px = x;
}
:
int **shifty;
allocation (&shifty);
// Now you can get at pointerArray via shifty.
至少在不使用全局變量的情況下是可移植的,但是我懷疑它也會被禁止。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.