码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 之Reference

时间:2017-09-30 10:10:15      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:follow   lang   sed   another   idt   wap   returns   绑定   地址   

 1.1 Reference define

    The reference variable is an alias(So, not allocate memory), Once the reference is initialized to a variable, you can use the reference name or variable name to point to the variable.

#include <iostream>
using namespace std;
int main(){
    int a = 99;       // declare simple variables
    int &b = a;       // declare reference variables & 读作引用
}
  • 引用在定义时需要添加&,在使用时不能添加&,使用时添加&表示取地址。
  • 不能建立数组的引用(wrong,int &&r=n), 因为数组是一个由若干个元素所成的集合,所以无法建立一个数组的别名。
  • 不能建立引用的引用(wrong,int &*p),不能建立指向引用的指针。因为引用不是一种数据类型,所以没有引用的引用,没有引用的指针。
  • 可以建立指针的引用(int *&q=p, 即给指针p起别名q),

1.2 References vs Pointers

  • Cannot have NULL references, be able to assume(能够假设) that a reference is connected to a legitimate piece of storage(一块合法的内存).
int &a ;  // Error, reference can not be empty must have a reference to the object
  • Once a reference is initialized to an object, it cannot be changed to refer to another object. Pointers can be pointed to another object at any time
#include<iostream>
using namespace std;
int main(void)
{
int a = 1; int b = 2; int& ra = a; //int& ra = b;// Error, multiple initialization return 0; }
  • A reference must be initialized when it is created. Pointers can be initialized at any time.

1.3 Reference application

  • 引用型参数(函数形参和实参是同一个对象)

         可以在修改形参的同时对实参的修改。 

         不存在对象复制,避免了对象的开销。

  • 传常引用(const, 避免函数对原来实参的意外修改)
  • 引用型返回值 

         从函数中返回引用,一定要保证在函数返回以后,被引用的目标一直有效,也就是不能返回函数体内的局部对象的引用,

         局部对象离开作用域就会被析构掉,所以不能返回对函数体内的局部对象的引用。

    1、Passing parameters by references
#include <iostream>
using namespace std;
void swap1(int a, int b);
void swap2(int *p1, int *p2);
void swap3(int &a, int &b);

int main(){
    int num1, num2;
    cout<<"Input two integers: ";
    cin>>num1>>num2;
    swap1(num1, num2);
    cout<<num1<<" "<<num2<<endl;
   
    cout<<"Input two integers: ";
    cin>>num1>>num2;
    swap2(&num1, &num2);            //指针则是地址调用
    cout<<num1<<" "<<num2<<endl;
   
    cout<<"Input two integers: ";
    cin>>num1>>num2;
    swap3(num1, num2);
    cout<<num1<<" "<<num2<<endl;

    return 0;
}

//直接传递参数内容
void swap1(int a, int b){
    int temp = a;
    a = b;
    b = temp;
}
//传递指针
void swap2(int *p1, int *p2){
    int temp = *p1;
    *p1 = *p2;
    *p2 = temp;
}
//按引用传参
void swap3(int &a, int &b){   //函数 形参 &
    int temp = a;
    a = b;
    b = temp;
}
  • swap1() 直接传递参数的内容,不能达到交换两个数的值的目的。a、b 是形参,是作用范围仅限于函数内部的局部变量,它们有自己独立的内存,和 num1、num2 指代的数据不一样。
  • swap2() 传递的是指针,能够达到交换两个数的值的目的。调用函数时,分别将 num1、num2 的指针传递给 p1、p2,此后 p1、p2 指向 a、b 所代表的数据,在函数内部可以通过指针间接地修改 a、b 的值。
  • swap3() 是按引用传递,能够达到交换两个数的值的目的。调用函数时,分别将 a、b 绑定到 num1、num2 所指代的数据,此后 a 和 num1、b 和 num2 就都代表同一份数据了,通过 a 修改数据后会影响 num1,通过 b 修改数据后也会影响 num2。
    2const reference
#include <stdio.h>

int main()
{
    int a    = 12;
    const int &ra  = a;     //const reference
    a =42;
    // ra =42 ;             //Error: The value of the target variable can not be modified by a const reference
    printf("a= %d,ra= %d\n",a,ra);
    return 0;
}
    3. return by reference
int Task1(int x, double y);    // uses return by value
int& Task2(int x, double y);  // uses return by reference

    Similar to pass by address(类似于传递地址), values returned by reference must be variables (you can not return a reference to a literal or an expression(文字或表达式的引用)). When a variable is returned by reference(通过引用返回变量), a reference to the variable is passed back to (传递给)the caller. The caller can then use this reference to continue modifying the variable.

    However, just like return by address, you should not return local variables(局部变量) by reference. Consider the following example:

int& doubleValue(int x)
{
    int value = x * 2;
    return value; // return a reference to value here
} // value is destroyed here
#include <iostream>
using namespace std;


// Global variable int num;

// Function declaration int& test(); int main() { test() = 5; cout << num; return 0; } int& test() { return num; }

    In program above, the return type of function test() is int&. Hence, this function returns a reference of the variable num.

    The return statement is return num;. Unlike return by value, this statement doesn‘t return value of num, instead it returns the variable itself (address).

    Important Things to Remember When Returning by Reference

  • Ordinary function returns value but this function doesn‘t. Hence, you cannot return a constant from the function.
int& test() {
    return 2;
}
  • You cannot return a local variable from this function.
int& test()
{
    int n = 2; 
    return n; 
}
#include <stdio.h>

int globalvar = 20;

int& foo()
{
    return globalvar;
}

int main()
{
    foo() = 10;   //left value
    printf("globalvar is : %d\n",globalvar);
    return 0;
}
#include <iostream>
using namespace std;

int & squareRef(int &);
int * squarePtr(int *);

int main() {
   int number1 = 8;
   cout <<  "In main() &number1: " << &number1 << endl;  // 0x22ff14
   int & result = squareRef(number1);
   cout <<  "In main() &result: " << &result << endl;    // 0x22ff14
   cout << result << endl;      // 64
   cout << number1 << endl;     // 64
   result = 100 ;               // adress ,result alias  
   cout << result << endl;      // 100
   cout << number1 << endl;     // 100

   int number2 = 9;
   cout <<  "In main() &number2: " << &number2 << endl;  // 0x22ff10
   int * pResult = squarePtr(&number2);
   cout <<  "In main() pResult: " << pResult << endl;    // 0x22ff10
   cout << *pResult << endl;   // 81
   cout << number2 << endl;    // 81
}

int & squareRef(int & rNumber) {
   cout <<  "In squareRef(): " << &rNumber << endl;      // 0x22ff14
   rNumber *= rNumber;
   return rNumber;
}

int * squarePtr(int * pNumber) {
   cout <<  "In squarePtr(): " << pNumber << endl;       // 0x22ff10
   *pNumber *= *pNumber;
   return pNumber;
}

1.4  reference and polymorphism

    Reference is another means of(手段) generating a polymorphic effect in addition to the pointer. This means that a reference to a base class can point to its derived(派生) class instance.

技术分享

 

C++ 之Reference

标签:follow   lang   sed   another   idt   wap   returns   绑定   地址   

原文地址:http://www.cnblogs.com/yunfung/p/7613279.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!