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

How to access a variable from a void return function in C++

本文关键字:返回 函数 访问 变量 void 中从 C++      更新时间:2023-10-16

我是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不返回任何内容,它只是进行计算并打印一些输出。由于项目的整个代码已经相当复杂,我想尽可能少地更改不是我编写的代码部分。我真的很感激你的帮助!

我假设这里有如下代码:

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

我假设external_function不需要任何参数,但如果它这样做真的无关紧要。

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

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

如果函数external_function返回双精度值,那么是的,您可以将其存储在双精度中,如问题所示。 那就完全没问题了。

如果您正在谈论的double变量是该函数中的局部变量,该变量未返回或存储在通过引用传递给函数的变量中,那么您没有任何方法可以获取该变量。

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

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

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

可以使用双精度类型的类成员变量。 将计算值"d"分配给成员变量。

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

或 可以从调用方法传递引用参数,并在外部函数中分配"d"的值。 例如:

externalFunction(double &updatedValue)
{
//do calculation of d
updatedValue =d;
}
void my_function()
{
double value;
externalFuntcion(value);
//now value will have the value of d;
}

模式 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