簡體   English   中英

c++ 試圖更改 function 之外的局部變量?

[英]c++ trying to change local variable outside of function?

我得到了以下程序:

#include <iostream>
using namespace std;

// ### write myFunction() ###

// ###

int main(){
    int x;
    cin >> x;
    myFunction(x);
    cout << "The Number + 1 is " << x;
}

我知道我應該將 x 更改為 x++,但是當 x 是 main() 中的局部變量時,我該如何在 myFunction() 中這樣做?

在 c++ 中,您可以通過reference function 來傳遞變量,這意味着您將從 function 訪問和寫入實際變量,而不是變量的副本:

myFunction(x); // doesn't change

void myFunction(int& x) // note the "&" (it means that x is a "reference" to an int)
{
    ++x;
}

這篇文章很好地描述了“參考”的東西。

正如@0x5453 提到的,更好的方法是從指針返回遞增的 integer 並將其分配給主變量,假設您被允許這樣做。

x = myFunction(x);

int myFunction(int x)
{
    return ++x;
}

暫無
暫無

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

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