繁体   English   中英

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

[英]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.

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