C++ - 在一个函数/文件中初始化变量然后在 main()/另一个文件中使用它的最佳方法是什么?

Vir*_*tus 1 c++ variables declaration

在 C++ 中,假设我需要为变量分配一些东西,我想在 main() 之外做这件事,所以代码更清晰,但是我想在 main() 或另一个函数中使用该变量进行某些操作。例如我有:

int main()
{
int a = 10;
int b = 20;
SomeFunction(a,b);
}
Run Code Online (Sandbox Code Playgroud)

我想要这样的东西:

void Init()
{
int a = 10;
int b = 20;
}

int main()
{
SomeFunction(a,b);
}
Run Code Online (Sandbox Code Playgroud)

但显然编译器会说 a 和 b 在 main() 的范围内未声明。我总是可以将它们声明为全局变量,但可能有更好的方法来解决这个问题,我读到全局变量从长远来看并不是那么好。我不想使用类。那么大家有什么建议呢?

Ada*_*amF 5

使用结构:

struct data
{
    int x;
    int y;
};

data Init()
{
    data ret;
    ret.x = 2;
    ret.y = 5;
    return ret;
}

int main()
{
    data v = Init();
    SomeFunction(v.x, v.y); //or change the function and pass there the structure
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果您不想使用偶数结构,那么您可以通过引用将值传递给 Init 函数。但在我看来,第一个版本更好。

void Init(int &a, int &b)
{
    a = 5;
    b = 6;
}

int main()
{
    int a, b;
    Init(a, b);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)