简体   繁体   English

从main()访问函数内部的静态变量,而无需使用C ++中的类

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

This is an assignment for my Object Oriented Programming class using C++. 这是我使用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. 更具体地说,我希望能够从“输入”功能访问在“分配”功能中初始化的指针x。 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. 如果没有allocation功能本身的合作,就无法以可移植的方式完成此任务。

Scoping rules prevent the use of x from outside the actual allocation function. 范围规则可防止在实际allocation函数之外使用x 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: 如果您被允许以某种方式更改 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.

That at least is portable without using a global but I suspect it'll be disallowed as well. 至少在不使用全局变量的情况下是可移植的,但是我怀疑它也会被禁止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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