c+中的普通引用和只读引用之间有什么区别+; 我是C++的新手,我对普通普通引用和只读引用之间的差异感到困惑。以下两点来自于

c+中的普通引用和只读引用之间有什么区别+; 我是C++的新手,我对普通普通引用和只读引用之间的差异感到困惑。以下两点来自于,c++,C++,引用必须在声明时初始化,并且不能随后修改。换句话说,您不能在以后的阶段使用引用来处理不同的变量 寻址常量对象的引用本身必须是常量,也就是说,它必须使用const关键字定义,以避免通过引用修改对象 我在想,怎么理解它?正常引用不同于只读(或常量)引用;因为只读引用可以指向常量对象,而不是普通引用。但以上两点确实令人困惑……尤其是“引用必须在声明时初始化,以后不能修改” 编辑:很抱歉,我之前没有说清楚。我想问的是,普通引用和只读引用之间有什么区别?目前它与指针无关 再次编辑:我终于明白了。为完整起见

引用必须在声明时初始化,并且不能随后修改。换句话说,您不能在以后的阶段使用引用来处理不同的变量

寻址常量对象的引用本身必须是常量,也就是说,它必须使用const关键字定义,以避免通过引用修改对象

我在想,怎么理解它?正常引用不同于只读(或常量)引用;因为只读引用可以指向常量对象,而不是普通引用。但以上两点确实令人困惑……尤其是“引用必须在声明时初始化,以后不能修改”

编辑:很抱歉,我之前没有说清楚。我想问的是,普通引用和只读引用之间有什么区别?目前它与指针无关

再次编辑:我终于明白了。为完整起见,以下是代码和注释

#include <iostream>
#include <string>
using namespace std;
int main(){
    string line(50, '-');

    /* a constant reference, non-constant object */
    int i=42;                 // a non-constant object
    const int& r1 =i;        // a constant reference r1, which reference the earlier defined variable i
    //r1 = 6*9;                // Error: tried to change the reference r1
    i = 50;
    cout << "r1: " << r1 << endl;
    cout << "i: " << i << endl;

    /* a constant reference, constant object */ 
    const int j = 40;
    // int& r2 = j;          // Error, because j is a constant, it requires a constant reference
    const int& r2 = j;
    // j = 45;              // Error, because j is a constant
    //r2 = 20;                // Error, because r2 is a constant reference

    /* non constant reference, non constant object */
    int k = 30;
    int& r3 = k;
    r3 = 10;                              // update 
    cout << "r3: " << r3 << endl;
    cout << "k: " << k << endl;
    cout << line << endl;
    k = 40;                              // update
    cout << "r3: " << r3 << endl;
    cout << "k: " << k << endl;

    return 0;
}
#包括
#包括
使用名称空间std;
int main(){
弦线(50’—’);
/*恒定的引用、非恒定的对象*/
int i=42;//一个非常量对象
const int&r1=i;//一个常量引用r1,它引用先前定义的变量i
//r1=6*9;//错误:试图更改引用r1
i=50;

CUT抱歉太幼稚。我认为指针和引用是相同的。所以它们不是。不是C++。一些C++语言引用C++中的指针,而不是指针。vel const或non const是同一件事,正如指针和引用是同一件事。然而,重要的一点是,在这种或那种情况下,更高级别的抽象控制着如何编写正确的代码。@kkxx,我添加了另一个副本,它应该能回答您澄清的问题。
/* how to understand a reference can not be used to address a different variable */
    int a = 1;
    int b = 2;
    int& r = a;              // r is a reference, which references variable (object) a
    r = b;                   // expect an error, but did not get an error
    cout<< "a: " << a << endl; //2
    cout<< "b: " << a << endl; //2
    cout<< "r: " << a << endl; //2