There's two ways, first the C++ way is to have a mutable (non-const
) reference:
void fun(int& b) {
b = 4;
}
// Calling
int x = 0;
fun(x);
Then the classic C way is to use a regular pointer:
void fun(int* b) {
*b = 4;
}
// Calling
int x = 0;
fun(&x);
The reference approach is better because there's less syntax chaff both in calling the function, and in the function's implementation. There's also no risk you might get nullptr
, a reference will be defined.
Note: Your use of new
here has unintended consequences, like leaking memory. When you allocate with new
you are responsible for releasing that memory.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…