zoukankan      html  css  js  c++  java
  • c++的引用

    /*#include"iostream"
    using namespace std;
    void any_function(int & p);//声明函数any_function//p为引用对象的别名
    int main()
    {
     int a = 1;
     cout << "a is" << a << endl;
     any_function(a); //此时引用对象的地址传过去的,而不是副本//因为在c和c++中‘&’是作为取地址符的,在c++中有复于了它引用的作用
     cout << "a is now" << a << endl;
     return 0;
    }
    void any_function(int & p)//引用时要在&前加上引用对象的类型,如“int”
    {
     cout << "p is" << p << endl;
     p = 2;//所以当p=2是cout << "a is now" << a << endl;输出结果为"a is now 2"//注意:引用变量之前必须将其初始化,像const一样必须在创建时对其初始化
    }
    */


    /*
    #include <iostream>
    using namespace std;
    float temp; //定义全局变量temp
    float fn1(float r); //声明函数fn1
    float &fn2(float r); //声明函数fn2
    float fn1(float r) //定义函数fn1,它以返回值的方法返回函数值
    {
     temp = (float)(r*r*3.14);
     return temp;
    }
    float &fn2(float r) //定义函数fn2,它以引用方式返回函数值
    {
     temp = (float)(r*r*3.14);
     return temp;
    }
    void main() //主函数
    {
     float a = fn1(10.0); //第1种情况,系统生成要返回值的副本(即临时变量)
     float c = fn2(10.0); //第2种情况,系统不生成返回值的副本
     //可以从被调函数中返回一个全局变量的引用
     float &d = fn2(10.0); //第3种情况,系统不生成返回值的副本
     //可以从被调函数中返回一个全局变量的引用
     cout << a << endl;
     cout << c << endl;
     cout<<d<<endl;
    }*/


    /*
    #include <iostream>
    using namespace std;
    int &put(int n);
    int vals[10];
    int error = -1;
    void main()
    {
     put(0) = 10; //以put(0)函数值作为左值,等价于vals[0]=10;
     put(9) = 20; //以put(9)函数值作为左值,等价于vals[9]=20;
     cout << vals[0]<<endl;
     cout << vals[9]<<endl;
    }
    int &put(int n)
    {
     if (n >= 0 && n <= 9) return vals[n];
     else { cout << "subscript error"; return error; }
    }*/
    //4、引用和多态
    //引用是除指针外另一个可以产生多态效果的手段。这意味着,一个基类的引用可以指向它的派生类实例。

    //class  A;
    //class  B:public A{ …… };
    //B  b;
    //A  &Ref = b; // 用派生类对象初始化基类对象的引用
    //Ref 只能用来访问派生类对象中从基类继承下来的成员,是基类引用指向派生类。如果A类中定义有虚函数,并且在B类中重写了这个虚函数,就可以通过Ref产生多态效果。

  • 相关阅读:
    英语影视台词---三、Cinema Paradiso
    英语影视台词---二、Inception
    智课雅思短语---二、exert positive/ negative effects on…
    MVC 编程模型及其变种
    四:redis的sets类型
    HDU 2048 号码塔(DP)
    删除句子UITableView额外的底线和切割线
    css+html菜单适应性学习的宽度
    删RAC中间ASM和LISTENER 资源的正确方法
    联合县城市,采用ajax,而使用ul模拟select下拉
  • 原文地址:https://www.cnblogs.com/maodun/p/6142931.html
Copyright © 2011-2022 走看看