hans

hans

【C++】Some Basic Tips in C++


Introduction#

Record some small tips for easy reference and consolidation of basic knowledge.

1. References &, Pointers *, and Address Operators &#

The reference & is a new concept in C++.

The address operator & obtains the address information of a variable.

A pointer points to a block of memory, and its content is the address of the memory it points to. A reference is an alias for a block of memory.

A reference must be initialized when defined, and can only be initialized once and cannot be changed afterwards. Pointers can be changed.

A reference cannot be empty, while a pointer can be empty.

Below is an example of "pass by value" program. Since the variable x in the body of the Func1 function is a copy of the external variable n, changing the value of x will not affect n, so the value of n remains 0.

Below is an example of "pass by pointer" program. Since the variable x in the body of the Func2 function is a pointer to the external variable n, changing the content of this pointer will cause the value of n to change, so the value of n becomes 10.

Below is an example of "pass by reference" program. Since the variable x in the body of the Func3 function is a reference to the external variable n, x and n are the same thing, changing x is equivalent to changing n, so the value of n becomes 10.

Pointers can be reassigned to point to another different object. References always point to the object specified at initialization.

2. Arrow (->) and Dot (.) Operators#

For a structure or class, if its object is defined as a pointer, use "->" to access class members or structure elements.

When defining a general object, use "." to access class members or structure elements.

For structures:

For classes:

3. Bitwise Operators & | << >> ^ ~ %#

http://blog.csdn.net/fox64194167/article/details/20692645

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.