C++ 指针与引用的区别

C++指针与引用的区别示意图

初学 C++ 指针时,我误以为可以将指针视作对于原始对象的引用,当时还没有接触 C++ 引用的概念,所以犯了概念上的错误,在此澄清一下这两者的区别。

在形式上使用 * 定义指针变量:int *p; 定义的时候可以不初始化。使用 & 定义引用:int &r = i; (其中 i 是另一个变量),定义引用的时候需要初始化,否则会报错:app.cpp:4:10: error: 'r' declared as reference but not initialized

对于 int i = 1;,分别定义 int &r = i; 和 int *p = i; 前者 r 被称为变量 i 的一个别称,它与 i 代表完全相同的对象,这意味着它们有相同的值以及相同的地址,就像下面的程序呈现的那样:

#include <iostream>
using namespace std;
int main() {
    int i = 1;
    int &r = i;
    cout << i << endl;
    // 1
    cout << r << endl;
    // 1
    cout << &i << endl;
    // 0x61fe14
    cout << &r << endl;
    // 0x61fe14
    return 0;
}

而后者,也就是 int *p = i; 则是重新开辟了一个内存区域用来存放变量 i 的内存地址,该地址就是指针 p 的值,也就是说变量 p 的地址是不同于变量 i 的地址的,可以用代码来验证这一点:

#include <iostream>
using namespace std;
int main() {
    int i = 1;
    int *p;
    *p = i;
    i = 1;
    cout << i << endl;
    // 1
    cout << *p << endl;
    // 1
    cout << &i << endl;
    // 0x61fe1c
    cout << &p << endl;
    // 0x61fe10
}

参考:

  • https://www.runoob.com/cplusplus/cpp-references.html
  • https://www.runoob.com/cplusplus/cpp-pointers.html
  • https://stackoverflow.com/questions/4643713/returning-a-reference-to-a-local-variable-in-c
posted @ 2024-04-25 18:48  gaotianchi  阅读(18)  评论(0编辑  收藏  举报