Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

pointers - how does the ampersand(&) sign work in c++?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The & has more the one meanings:

1) take the address of a variable

int x;
void* p = &x;
//p will now point to x, as &x is the address of x

2) pass an argument by reference to a function

void foo(CDummy& x);
//you pass x by reference
//if you modify x inside the function, the change will be applied to the original variable
//a copy is not created for x, the original one is used
//this is preffered for passing large objects
//to prevent changes, pass by const reference:
void fooconst(const CDummy& x);

3) declare a reference variable

int k = 0;
int& r = k;
//r is a reference to k
r = 3;
assert( k == 3 );

4) bitwise and operator

int a = 3 & 1; // a = 1

n) others???


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...