[英]How to define a variable in a function and access and change it in another function?(c++)
我想知道如何在一个函数中定义一个变量并在另一个函数中访问和更改它。 例如:
#include <iostream>
void GetX()
{
double x = 400;
}
void FindY()
{
double y = x + 12;
}
void PrintXY()
{
std::cout << x;
std::cout << y;
}
int main()
{
GetX();
FindY();
PrintXY();
}
我将如何从所有函数访问这些变量? (显然,为了在现实生活中工作,我不需要这么多功能,但我认为这是一个很好的简单示例)。 在此先感谢您的帮助!
使用函数参数将值传递给函数并返回值以返回结果:
#include <iostream>
double GetX()
{
return 400;
}
double FindY(double x)
{
return x + 12;
}
void PrintXY(double x, double y)
{
std::cout << x;
std::cout << y;
}
int main()
{
double x = GetX();
double y = FindY(x);
PrintXY(x, y);
}
由于问题被标记为C++
,这里是另一种选择:
#include <iostream>
class Sample
{
public:
void FindY()
{
y = x + 12;
}
void PrintXY()
{
std::cout << x;
std::cout << y;
}
private:
double x = 400, y;
};
int main()
{
Sample s;
s.FindY();
s.PrintXY();
}
1st,使 x, y 为static
,以便在函数返回时它们存在.. 2nd,获取引用,修改或在函数之外做一些事情..
#include <iostream>
double &GetX()
{
static double x = 400;
return x;
}
double &FindY( double x )
{
static double y;
y = x + 12;
return y;
}
void PrintXY(double x, double y )
{
std::cout << x;
std::cout << y;
}
int main()
{
double &x = GetX();
double &y = FindY( x );
// Now you can modify x, y, from Now On..
// .....
PrintXY( x, y );
}
顺便说一句,我不推荐这种风格的代码..
您想在一个函数中定义一个变量:这意味着您将变量设为该函数的局部变量。
您想从另一个函数访问和更改该局部变量。 这是不寻常的。 技术上可行,但可以通过更好的资源管理/设计来完成。
*您可以将变量设为您的班级成员并使用它。
*您也可以通过将变量设为全局来共享变量。
*以棘手的方式:
double &GetX()
{
static double x = 400;
return x;
}
// We are accessing x here to modify y
// Then we are modifying x itself
// Pass x by reference
double &AccessAndChangeX(double& x)
{
static double y;
y = x + 12; // We are accessing x here and using to modify y.
// Let's modify x
x = 100;
return y;
}
void PrintXY(double x, double y)
{
std::cout << x;
std::cout << y;
}
int main()
{
double &x = GetX(); // Take the initial value of x. 400.
double &y = AccessAndChangeX(x);
//Print initial value of x and value of y(generated using x)
PrintXY(x, y);
// X was modified while AccessAndChangeX(x). Check if x was changed!
std::cout << "\n" << "What is the value of x now : " << GetX();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.