c++引用 &const 应用

    科技2025-11-27  17

    引用

    概念: 1.定义引用时,一定要将其初始化成引用某个变量。 2.初始化后,它就一直引用该变量,不会再引用其他变量。 3.引用只能引用变量,不能引用常量和表达式 例如 int n=4; int &r =n;//r引用了n,r的类型是int & 某个变量的引用,等价于这个变量,相当于该变量的一个别名。

    下面第一个例子不太实际。

    void swap(int &a ,int &b) { int tmp; tmp =a; a=b; b=tmp; } int main(){ int n1,n2; swap(n1,n2);//n1,n2值被交换。 }

    下例很有实际意义:

    int n=4; int & setValue(){return n;} int main (){ setValue() =40; cout << n ; //输出40 return 0; }

    常引用 const +&

    int n; const int & r =n;// r的类型是 const int & 。 特点:不能通过常引用去修改其引用的内容。 int n =10; const int & r =n; r=100; //编译错误 n=200 ;//编译正确

    const 应用

    1)定义常量 const int n=4; const double m= 3.4; const char *p =“ssss”;

    2)定义常量指针

    int n,m; const int *p =&n; *p =5;//编译出错 n=100;//编译通过 p=&m;// 编译通过,常量指针的指向可以变化

    不能把常量指针赋值给非常量指针。反过来可以 const int *p1,int *p2; p1=p2;//编译通过 p2=p1;//编译出错 p2=(int *) p1;//编译通过,强制转化

    函数参数为常量指针时,可以避免函数内部不小心改变函数参数所指的地方

    void myprintf(const char *p) { strcpt(p,"this");//编译出错 myprintf("s%",p);//编译ok }
    Processed: 0.017, SQL: 9