关于C++中&(reference operator)与引用、*(dereference operator)与指针的概念混淆咨询
Hey there, let’s break down the dual roles of & and * in C++—they can feel confusing at first, but once you pay attention to their context, it all clicks!
The
& Operator: Two Meanings, Same Symbol This operator is called the reference operator, but it serves two distinct purposes:
- "取地址" (Address Retrieval): When used in an assignment like
a = &b;(note:ashould be a pointer type to hold this address, e.g.,int* a = &b;),&grabs the memory address of variableband stores it ina. Essentially, it’s asking for the exact location whereblives in memory. - "引用" (Alias Declaration): When it appears in a variable declaration like
int &a = b;,&definesaas an alias forb. This meansais just another name for the same variable—any operation onadirectly affectsb, since they refer to the exact same piece of memory.
The
* Operator: A Two-Faced Tool Too Known as the dereference operator, it also has two key meanings:
- Pointer Declaration: When you’re declaring a variable like
int* p;, the*tells the compiler thatpis a pointer—a variable built to hold the memory address of another variable. You’ll often initialize it with the address-of&, likeint* p = &b;. - 解引用 (Dereferencing): When used on an existing pointer (e.g.,
int val = *p;),*does the reverse of the address-of&: it takes the address stored inpand retrieves the actual value stored at that memory location. Think of it as accessing the content that the pointer is pointing to.
内容的提问来源于stack exchange,提问作者Junu
相关产品推荐
相关产品推荐

