C和C++中*与&的用法

来源:互联网 发布:黑产数据交易平台 编辑:程序博客网 时间:2024/06/03 21:48

The use of * in C


(a)   Multiplication乘法:   x = y*z;


(b)    Multiply-assign:   x *= y;   Means the same as: x = x*y;


(c)   Comments: 注释  /* your comment here */


(d)   Pointer declarations指针声明:   int *p; or int* p;   Read: p is a pointer to an int.


(e)   Compound pointers:   int **p; or int** p;   Read: p is a pointer to a pointer to an int. 
(Also int ***p; and so on.)


(f)   De-referencing:   x = *p;   Read: Assign to x the value pointed to by p.




The use of & in C
(a)   Logical-and逻辑与:   if ( ( a>1 ) && (b<0) ) ...
(b)   Bitwise-and:   x = a&b;   Corresponding bits are and'ed (e.g. 0&1 -> 0)
(c)   Bitwise-and-assign:   x &= y;   Means the same as: x = x&y;
(d)   Address-of operator: 取地址  p = &x;   Read: Assign to p (a pointer) the address of x.


The additional use of & (in parameters) in C++

C++ uses a type of variable called a "reference"(引用) variable (or simply a "reference") which is not available in C (although the same effect can be achieved using pointers).在c中不可用,但指针可实现与引用相同的效果


References, pointers and addresses are closely related concepts. Addresses are addresses in computer memory (typically the address in memory where the value of some variable is stored), e.g. (in hexadecimal) 0xAB32C2. Pointers are variables which hold addresses, and so "point to" memory locations (and thus to the values of variables). Conceptually, reference variables are basically pointers by another name (but may not be instantiated as such by the compiler).


It is possible to declare a reference within a function, like other variables, e.g.


void main(void) 

int i; 
int& r = i; 
...
}

but this is pointless, since the use of the reference is equivalent to the use of the variable it references.


References are designed to be used as parameters (arguments) to functions, e.g.


#include <iostream.h>


void f(int& r);


void main(void) 

int i=3;


f(i); 
cout << i; 
}


void f(int& r) 

r = 2*r; 
}

This program prints "6" (2*r doubles the value of the variable referenced by r, namely, i).

We could do the same in C by declaring f() as void f(int *r), in which case r is a pointer to an int, then calling f() with argument &i (address-of i), and using de-referencing of r within f(), but clearly C++ provides a more elegant way of passing values to functions (by reference) and returning (perhaps multiple) values from functions (without use of a return statement).


int &get();清晰起见,写成:int& get();。int&是成员函数get()的返回值类型,即int的引用类型。与直接返回int相比,返回引用不会传递返回值对象本身(而是传递返回值的地址——引用的底层一般使用地址实现),通过返回的引用在函数体外仍然可以对返回对象进行操作,但没有直接返回对象的开销。
对于复杂的类对象来说,使用引用传递参数优势比较明显。此外,返回引用在此基础上可以实现一些特殊的效果,例如cout从属的ostream类的<<操作符重载函数可以隐含ostream&参数并返回一个对象自身的引用,借此在<<左端传入<<后的cout返回的自身引用可以作为(右边)后继表达式的参数,进行连续迭代操作。
应该注意,返回的引用不能是关于函数体内自动变量的,因为这些变量位于栈上,函数调用结束后就被销毁,返回的引用会无效。


原创粉丝点击