zoukankan      html  css  js  c++  java
  • 指针及引用传参的一个实例

    最近在看代码时,发现了一个有趣的事,通过指针和引用传参,能够在不使用返回值就能实现数据的获取。

    #include <stdio.h>
    #include <string.h>
    #include <iostream>
    
    using namespace std;
    
    struct Test
    {
        int i;
        char buf[12];
    };
    
    void fun1(int &num)
    {
        num = 25;
    }
    
    void fun2(char &buf)
    {
        buf = 'A';
    }
    
    void fun3(char *buf)
    {
    
        strncpy(buf,"hello",6);
    }
    
    void fun4(Test &test)
    {
        test.i = 38;
        strncpy(test.buf,"hello world",12);
    
    }
    int main(int argc, char const *argv[])
    {
        /* code */
        int num;
        char buf1;
        char buf2[6];
        fun1(num);
        fun2(buf1);
        fun3(buf2);
    
        cout << num << endl << buf1 << endl << buf2 <<endl;
    
        Test te;
        fun4(te);
        cout << te.i << endl << te.buf << endl;
        
        return 0;
    }

    使用这种格式简化了代码。

    输出打印结果:

    25
    A
    hello
    38
    hello world

  • 相关阅读:
    面向对象三 组合 特殊成员
    面向对象二 成员 嵌套
    面向对象
    模块和包
    异常处理
    os模块和序列化模块
    常用模块一
    常用模块 re模块
    内置函数二
    Algs4-2.2.14归并有序的队列
  • 原文地址:https://www.cnblogs.com/KeepThreeMunites/p/11341428.html
Copyright © 2011-2022 走看看