C++Reference(引用)

版权声明:未经允许不得私自转载,一旦发现严惩不贷!!! https://blog.csdn.net/Oneplus6/article/details/79312553
1,引用并非对象,只是一个已经存在的对象起的别名
2,引用只能绑定在对象上,不能与字面值或某个表达式的结果绑定在一起
int &ref_value = 10;  //wrong
3,引用必须初始化,所以引用之前不需要测试其有效值,因此使用引用·可能会比使用指针效率高。
4,将引用变量作参数时,函数将使用原始数据,而非副本
4,,如果想要引用指向常量需:
const double& ref = 100;
int int_value = 1024;
//refValue指向int_value, 是int_value的另一个名字
int& refValue = int_value;
//Wrong:引用需被初始化
int& refValue2;
示例:
int num = 100;
int& ref_num = num;
ref_num = 118;
cout << &num << '\t' << &ref_num << endl;
//使用引用传参
void Swap1(int, int);
void Swap2(int*, int*);
void Swap3(int&, int&);
void Swap1(int num1, int num2)
{
    int temp;
    temp = num1;
    num1 = num2;
    num2 = temp;
}
void Swap2(int* p1, int* p2)
{
    int temp;
    temp = *p1;
    *p1 = *p2;
    *p2 = temp;
}
void Swap3(int& ref1, int& ref2)
{
    int temp;
    temp = ref1;
    ref1 = ref2;
    ref2 = temp;
}
int main()
{
    SetConsoleTitle("My class note");
    int num1 = 10, num2 = 5;
    Swap1(num1, num2);
    cout << "Swap1:" << num1 << '\t' << num2 << endl;
    Swap2(&num1, &num2);
    cout << "Swap2:" << num1 << '\t' << num2 << endl;
    Swap3(num1, num2);
    cout << "Swap3:" << num1 << '\t' << num2 << endl;
 return 0;
}
函数返回引用类型

猜你喜欢

转载自blog.csdn.net/Oneplus6/article/details/79312553