簡體   English   中英

如何在函數中定義變量並在另一個函數中訪問和更改它?(C++)

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM