zoukankan      html  css  js  c++  java
  • c++代码中“引用”的使用

    这些上机实验在Qt5.9上完成的,具体步骤

    • 结构体引用
    #include <iostream>
    #include<stdlib.h>
    using namespace std;
    struct mycoach
    {
        string name;
        int age;
    };
    
    void *addcoachinfo(mycoach * &cpc,string name,int age)
    {
        cpc=(mycoach*)malloc(sizeof(mycoach));
        cpc->name=name;
        cpc->age=age;
        cout<<"大家好我是"<<cpc->name<<"今年芳龄"<<cpc->age<<endl;
        free(cpc);
        cpc=NULL;
    }
    
    int main()
    {
        mycoach *cpc=NULL;
        addcoachinfo(cpc,"陈培昌",22);
        return 0;
    }

    •  引用分为普通引用和常引用
    int main()
    {
        int a=10;
        int &aa =a;
        aa=88;
        printf("%d
    ",aa);
        return 0;
    }

    常引用的目的往往是不希望被修改

    引用实际上是内存的别名,由于字面量没有地址,因此第9行的代码有误

    正确的做法是第10行

    函数中常引用,目的是让实际参数只拥有只读属性

    • 对指针的引用
    #include <iostream>
    
    using namespace std;
    
    struct mycoach
    {
        string name;
        int age;
    };
    
    int main()
    {
        mycoach *cpc = (mycoach*)malloc(sizeof(mycoach));
        cpc->name="陈培昌";
        mycoach * &wr=cpc;
        wr->name="魏锐";
        cout <<cpc->name<< endl;
        return 0;
    }

    •  对比:常量引用
    #include <iostream>
    
    using namespace std;
    
    struct mycoach
    {
        string name;
        int age;
    };
    
    void showinfo(const mycoach &cpc)
    {
        //cpc.name="中国队长";如果去掉注释就报错,常量不可修改
        cout<<"hello! I'm"<<cpc.name<<endl;
    }
    
    int main()
    {
        mycoach *cpc = (mycoach*)malloc(sizeof(mycoach));
        cpc->name="陈培昌";
        const mycoach &wr=*cpc;//常量引用只能引用字面量
        showinfo(wr);
        return 0;
    }

  • 相关阅读:
    python之路之模块
    python之路xml模块补充
    python之路模块补充
    python之路模块简介及模块导入
    python之路正则补充模块
    python之路模块
    [Unity算法]A星寻路(一):基础版本
    [Unity基础]RenderTexture
    [Lua]位运算
    [Unity插件]AI行为树使用总结
  • 原文地址:https://www.cnblogs.com/saintdingspage/p/12000294.html
Copyright © 2011-2022 走看看