如何从C ++中的void返回函数访问变量

时间:2017-08-03 02:23:59

标签: c++

我是C ++的新手,我正在为一个相当大的项目做贡献。我写了一段代码,我正在调用一个执行大量计算的外部函数。

我需要external_function()完全运行,但我还需要在external_function()期间计算的特定变量(双精度)的值。我想在my_function()中存储或至少使用此变量的值。这可能吗?

的内容
double my_variable = external_function(external_variable);

请注意,代码如下所示:

void external_function()
{
    double d;
    // perform calculations on d
}

void my_function()
{
    ...
    external_function();
    ...
}

不幸的是,external_function没有返回任何内容,只是进行计算并输出一些输出。由于项目的整个代码已经相当复杂,我想尽可能少地改变代码中未编写的部分。我真的很感谢你的帮助!

5 个答案:

答案 0 :(得分:3)

我在这里假设你有以下代码:

void external_function()
{
    double d;
    // perform calculations on d
    ...
    // print d
    std::cout << d;
}

void my_function()
{
    ...
    external_function();
    ...
}

我假设external_function没有参数,但如果确实没有参数,那就无所谓了。

您可以通过将返回类型修改为external_function来更改double

double external_function()
{
    double d;
    // perform calculations on d
    ...
    // print d
    std::cout << d;
    return d;
}

仍然可以安全地调用该函数:

external_function();

没有捕获返回值,因此不需要更新它的其他用途。有些静态代码分析器可能会让你无视忽略函数的返回值,但如果你愿意,你可以为它们写一个例外。

现在这意味着你可以像这样调用它:

double value = external_function();

您的第二个选择是将可选参数传递给external_function()

void external_function(double* out = nullptr)
{
    double d;
    // perform calculations on d
    ...
    // print d
    std::cout << d;
    if (out)
        *out = d;
}

同样的事情是:调用者仍然可以调用此函数而不改变他们调用它的方式:

 external_function();

但这意味着您现在可以这样称呼它:

double value = 0.0;
external_function(&value);
// value now contains the same value as d

答案 1 :(得分:2)

如果函数external_function返回double,则是,您可以将其存储在问题中显示的double中。那将是完美的。

如果你所讨论的double变量是该函数中的一个局部变量,它没有返回或存储在通过引用传递给函数的变量中,那么你就没有任何方法可以获取它。 / p>

答案 2 :(得分:1)

是的,可以将external_function(external_variable)的值存储在变量中。

请务必检查external_function的返回类型是否为double,因此会返回一个double值。你需要像这样编码:

    double external_function() {
           double returnedValue;
           // your code here
           cout << calculationOutputValue << endl;
           return returnedValue;
    }

答案 3 :(得分:0)

模式1:使用void external_function(),添加参数。

void external_function(double* pValue)
{
    *pValue = external_value;
    // operation of external_value
    // external_value = 142.14
}

获得结果

void call_function()
{
    double pValue = 0.0;
    external_function(&pValue);
    cout<<pValue<<endl;
}

结果:142.14

模式2:不使用参数功能,修改功能的返回类型。

double external_function()
{
    // do something you want...
    // external_value = 142.14;
    return external_value;
}

获得结果

void call_function()
{
    double pValue;
    pValue = external_function();
    cout<<pValue<<endl;
}

结果:142.14

答案 4 :(得分:0)

您可以使用double类的类成员变量。 分配&#34; d&#34;的计算值到成员变量。

现在,您可以在班级的任何方法中使用此成员变量。

或 您可以从调用方法传递参考参数,并指定&#34; d&#34;的值。在外部功能。 例如:

externalFunction(double &updatedValue)
{
//do calculation of d
updatedValue =d;
}

void my_function()
{
double value;
externalFuntcion(value);
//now value will have the value of d;
}