C++ Primer学习2:细节:引用

来源:互联网 发布:迪曼宠物用品淘宝真假 编辑:程序博客网 时间:2024/06/06 05:12

引用是对象或变量的的别名,对引用变量的操作相当于对被引用变量的操作。

定义:类型 & 变量名

初始化:引用类型变量必须初始化;  初始化关联到其他类型的变量

#include <iostream>using namespace std;int main(){    int ival = 10;    int &refVal = ival;    int &refVal2;   //error: ‘refVal2’ declared as reference but not initialized|    int &refVal3 = 10; //error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’|        return 0;}

const 引用

const引用是指向const对象或变量的引用; const应用必须引用变量与被引用变量都是const类型

    const int t = 4;    const int &reft = t;     int &reft2 = t; //error: invalid initialization of reference of type ‘int&’ from expression of type ‘const int’|



0 0
原创粉丝点击