Int函数参数不能正常工作

int function parameter not working properly

本文关键字:工作 常工作 函数 参数 不能 Int      更新时间:2023-10-16

我想在c++中做一些事情,我有一个问题。我有这样的代码:

#include <iostream>
#include <string>
//---MAIN---
using namespace std;
int af1 = 1;
int af2 = 1;
void lettersort(int cnt1) {
    cout << "RESULT:" << cnt1 << endl;
    cnt1++;
    cout << "RESULT WHEN+:" << cnt1 << endl;
    cout << "RESULT IN GLOBAL INT:" << af2 << endl;
}
int main()
{
    lettersort(af2);
    return 0;
}

那么有没有办法让cnt1++也影响af2,使其变大呢?我不想直接使用af2++,因为我有时想使用af1

目前您只是通过值将af2传递给cnt1 ,因此对cnt1的任何更改都严格限于lettersort函数。为了获得您想要的行为,您需要通过引用传递cnt1参数。变化:

void lettersort(int cnt1)

:

void lettersort(int &cnt1)

您通过值传递参数。也就是说,将af1的值复制到lettersort的局部变量中。然后这个整数被加1,并在函数结束时被处理掉,而不影响原来的af1。如果您希望该函数能够影响af1,则应该通过引用传递参数:

void lettersort(int& cnt1) { // Note the "&"

如果我没理解你的问题:

有两种方法可以做到这一点。

  1. make lettersort function返回新值,并将其放入af2

    int lettersort(int cnt1) {
        cout << "RESULT:" << cnt1 << endl;
        cnt1++;
        cout << "RESULT WHEN+:" << cnt1 << endl;
        cout << "RESULT IN GLOBAL INT:" << af2 << endl;
        return cnt1;
    }
    int main()
    {
    af2 = lettersort(af2);
    return 0;
    }
    
  2. 通过引用传递值。你可以在这里读到,但通常它是传递一个指向那个值的指针。这意味着无论你对你传递的参数做什么,都会发生在原始的var上。

的例子:

    void foo(int &y) // y is now a reference
    {
        using namespace std;
        cout << "y = " << y << endl;
        y = 6;
        cout << "y = " << y << endl;
    } // y is destroyed here
    int main()
    {
        int x = 5;
        cout << "x = " << x << endl;
        foo(x);
        cout << "x = " << x << endl;
        return 0;
    }

  • 这里你只需要修改参数传递给lettersort
  • 例如,如果您声明并初始化任何变量,如:

      int a=10;    int &b = a;
    
  • 现在a和b指向相同的值。如果你改变a,那么

  • ,

      cout << a; cout << b;
    
  • 两个语句在整个程序中产生相同的结果。所以使用这个概念我修改了函数参数,把它写成by参考。

  • 你的正确代码是:

      #include <iostream>
    
      #include <string>
      using namespace std;
      int af1 = 1;
      int af2 = 1;
      void lettersort(int &cnt1) {
      cout << "RESULT:" << cnt1 << endl;
      cnt1++;
      cout << "RESULT WHEN+:" << cnt1 << endl;
      cout << "RESULT IN GLOBAL INT:" << af2 << endl;
      }
      int main()
      {
      lettersort(af2);
      return 0;
      }