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.
void Func1(int x)
{
x = x+10;
}
int n = 0;
Func1(n);
cout << "n=" << n << endl;
// Output: n = 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.
void Func2(int* x)
{
(*x) = (*x) + 10; // * is used to dereference the pointer, x itself represents the address information of n.
}
int n = 0;
Func2(&n); // Here & is the address operator
cout<<"n="<<n<<endl;
// Output: n=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.
void Func3(int &x)
{
x = x+10;
}
int n = 0;
Func3(n);
cout<<"n="<<n<<endl;
// Output: n=10
Pointers can be reassigned to point to another different object. References always point to the object specified at initialization.
string s1("Nancy");
string s2("Clancy");
string& rs = s1; // rs references s1
string *ps = &s1; // ps points to s1
rs = s2; // rs still references s1, but the value of s1 is now "Clancy"
ps = &s2; // ps now points to s2
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:
struct MyStruct
{
int member_a;
};
MyStruct s;
s.member_a = 1;
MyStruct *ps;
(*ps).member_a = 1;
ps->member_a = 2;
For classes:
class A
{
public:
void play();
};
A *p;
p->play();
A p;
p.play();