zoukankan      html  css  js  c++  java
  • C/C++系列之复杂引用

    以struct类型为例:

    • 引用
    #include"iostream"
    #include<string>
    using namespace std;
    struct mycoach
    {
        string name;
        int age;
    };
    
    void printinfo1(mycoach &cpc)
    {
        //参数是mycoach实例的别名,指向入参的真实地址,所以一改入参的值也跟着改
        cpc.name = "陈培昌";
    }
    
    void main()
    {
        mycoach coach1;
        coach1.name = "徐晓冬";
        printinfo1(coach1);
        cout << "这位神秘嘉宾是" << coach1.name << endl;//陈培昌
        system("pause");
    }

    输出结果:

    •  形参传入----可以预见这种方式不会改变struct实例的值
    #include"iostream"
    #include<string>
    using namespace std;
    struct mycoach
    {
        string name;
        int age;
    };
    
    void printinfo1(mycoach cpc)
    {
        //参数是mycoach实例的别名,指向入参的真实地址,所以一改入参的值也跟着改
        cpc.name = "陈培昌";
    }
    
    void main()
    {
        mycoach coach1;
        coach1.name = "徐晓冬";
        printinfo1(coach1);
        cout << "这位神秘嘉宾是" << coach1.name << endl;
        system("pause");
    }

    输出结果:

    •  指针---效果同引用
    #include"iostream"
    #include<string>
    using namespace std;
    struct mycoach
    {
        string name;
        int age;
    };
    
    void printinfo3(mycoach *cpc)
    {
        //和引用效果一样,入参为指针类型,可以更改指向地址的数据
        cpc->age = 40;
        cout << "hello, myname is " << cpc->name << "今年芳龄" << cpc->age << endl;
    }
    
    void main()
    {
        mycoach coach1;
        coach1.name = "徐晓冬";
        mycoach *xxd = &coach1;
        printinfo3(xxd);
        cout << "这位神秘嘉宾是" << coach1.name << endl;
        system("pause");
    }

    输出结果:

     通过代码可以看出,函数中传入的指针和struct实例处于同一内存地址上

    #include"iostream"
    #include<string>
    using namespace std;
    struct mycoach
    {
        string name;
        int age;
    };
    
    void printinfo3(mycoach *cpc)
    {
        //和引用效果一样,入参为指针类型,可以更改指向地址的数据
        cpc->age = 40;
        cout << "hello, myname is " << cpc->name << "今年芳龄" << cpc->age << endl;
        printf("内存地址是%d
    ",cpc);
    }
    
    void main()
    {
        mycoach coach1;
        coach1.name = "徐晓冬";
        mycoach *xxd = &coach1;
        printinfo3(xxd);
        cout << "这位神秘嘉宾是" << coach1.name << endl;
        printf("struct实例地址是%d
    ", &coach1);
        system("pause");
    }

  • 相关阅读:
    TSQL 错误状态
    CSS光标聚焦改指针为手
    PD使用指导
    Ext 为label添加单击事件
    (转) SQL Server中解决死锁的新方法介绍
    DateTime 的使用技巧
    (转) C# 接口
    常见频率f与周期T之间的关系
    上拉电阻与下拉电阻的作用和区别
    powershell命令返回值
  • 原文地址:https://www.cnblogs.com/saintdingspage/p/11939309.html
Copyright © 2011-2022 走看看