簡體   English   中英

int 函數參數工作不正常

[英]int function parameter not working properly

我正在嘗試用 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函數lettersort本地。 為了獲得您想要的行為,您需要通過引用傳遞您的cnt1參數。 改變:

void lettersort(int cnt1)

到:

void lettersort(int &cnt1)

您正在按值傳遞參數。 即,您正在將af1的值復制到lettersort的局部變量。 然后這個整數被遞增,並在函數結束時被處理掉,而不影響原來的af1 如果您希望函數能夠影響af1 ,您應該通過引用傳遞參數:

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

如果我理解你的問題:

有兩種方法可以做到這一點。

  1. 使lettersort函數返回新值,並將其放入 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. 通過引用傳遞值。 你可以在這里閱讀它,但通常它是關於傳遞一個指向該值的指針。 這意味着無論你在傳遞的參數上做什么,都會發生在原始變量上。

例子:

    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,則更改也會反映在 b 中。

  • 所以,

     cout << a; cout << b;
  • 這兩個語句在整個程序中產生相同的結果。 所以使用這個概念我修改了函數參數並將其作為引用。

  • 您的正確代碼是:

     #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; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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