简体   繁体   中英

Access static variables inside functions from main() without classes in C++

This is an assignment for my Object Oriented Programming class using C++. In this program, I need to be able to access a static pointer initialized in one function from another function. To be more specific, I'd like to be able to access pointer x initialized in the "allocation" function from the "input" function. And before anyone asks, I am not allowed to use any global variables.

#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;
}

This cannot be done in a portable way without the co-operation of the allocation function itself.

Scoping rules prevent the use of x from outside the actual allocation function. Its duration may be outside the function (being static) but its scope (ie, its visibility) is not.

There may be hacks you can use in some implementations but, if you're going to learn the language, you'd better learn the language proper rather than relying on tricks that won't work everywhere.

If you were allowed to change the allocation function somehow, I'd look into something like this:

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.

That at least is portable without using a global but I suspect it'll be disallowed as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM