【问题标题】:How to use a variable from other functions如何使用来自其他函数的变量
【发布时间】:2021-05-27 09:34:08
【问题描述】:
int calculateX()
{
    
    int x;
    cout<<"Enter value for x: ";
    cin>>x;
    return x;
}

int anotherFunction()
{
    /////
}

int main()
{
    calculateX();
    anotherFunction();
    
    return 0;
    
}
    

这是一个代码示例。我如何才能将用户在 calculateX() 函数中的输入用于函数 anotherFunction() ?

【问题讨论】:

  • int anotherFunction(int)? (和anotherFunction(calculateX()); 用法或类似)
  • 只需添加一个int 参数并使用anotherFunction(calculateX()); 调用它calculateX 的返回值存在那里是有原因的。

标签: c++


【解决方案1】:

你必须使用函数参数:

int calculateX()
{    
    int x;
    cout<<"Enter value for x: ";
    cin>>x;
    return x;
}

int anotherFunction(int x)
{
    /////
}

int main()
{
    int x = calculateX();
    anotherFunction(x);
    
    return 0;    
}

【讨论】:

    【解决方案2】:

    您需要的是已经回答的值传递或像这样的全局变量

    #include <iostream>
    using namespace std;
    // Global variable declaration:
    int g;
    int anotherFunction()
        {
            cout << g;
        }
    int main () {
       // Local variable declaration:
       int a, b;
       a = 10;
       b = 20;
       g = a + b;
       anotherFunction();
       return 0;
    }
    

    任何函数都可以访问全局变量。也就是说,全局变量在声明后可在整个程序中使用。

    【讨论】:

    • 我强烈建议不要使用全局变量。阅读this post,还有很多其他...
    【解决方案3】:

    您必须将变量 x 声明为全局变量(在calculateX() 函数之外),以便anotherFunction() 可以看到它。如果在calculateX()函数内部定义变量x,退出函数后会被删除。

    int x;
    int calculateX()
    {   
        cout<<"Enter value for x: ";
        cin >> x;
        return x;
    }
    
    int anotherFunction()
    {
        /////
    }
    
    int main()
    {
        calculateX();
        anotherFunction();
        return 0;
        
    }
    

    【讨论】:

      【解决方案4】:

      函数通常在其名称之前具有返回类型。例如:

      int calculateX() {   
          int x;
          cout<<"Enter value for x: ";
          cin>>x;   
          anotherFunction(x)
          return x;
      }
      

      int 是这里的返回类型。您正在从主函数调用两个函数。 calculateX 有一个名为 x 的 int 类型变量。因此,您不能从 calculateX 范围之外访问 x 。但是您可以将它返回到您的主函数并将其存储在不同的变量中,以便它在主函数中可用。一旦它可用,您可以将它作为参数发送给另一个函数。在你的情况下应该是这样的:

      int anotherFunction(int valueFromMain)
      {
         std::cout << valueFromMain << std::endl;
      }
      
      int main(){
          int returnedFromCalculateX = calculateX(); //You have returned value available on main Function
          anotherFunction(returnedFromCalculateX); //Send It to anotherFunction(pass by value)
          return 0;    
      }
      

      您也可以将值作为参考发送。这需要更高的理解。详情请查看:https://www.w3schools.com/cpp/cpp_function_reference.asp

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-11-25
        • 2018-08-15
        • 2021-07-29
        • 2021-01-02
        • 1970-01-01
        • 2021-03-31
        • 1970-01-01
        相关资源
        最近更新 更多