zoukankan      html  css  js  c++  java
  • C++ 利用指针和数组以及指针和结构体实现一个函数返回多个值

    C++ 利用指针和数组实现一个函数返回多个值
    demo1

    #include <iostream>
    using namespace std;
    int* test(int,int,int);
    int main()
    {
    int * result =test(1,2,3);
    cout<<result[0]<<endl<<result[1]<<endl<<result[2]<<endl;
    getchar();
    return 0;
    }
    
    int * test(int a,int b,int c)
    {
    int* presult =new int[3];
    presult[0] =a;
    presult[1] =b;
    presult[2] = c;
    return presult;
    }

    输出

    1 
    2 
    3


    C++ 利用指针和结构体实现一个函数返回多个值
    demo2

    #include <iostream>
    using namespace std;
    struct result
    {
    int first;
    double second;
    };
    result test(int a,double b);
    int main()
    {
    result returnvalue =test(1,2.1234);
    cout<<returnvalue.first <<endl<<returnvalue.second<<endl;
    getchar();
    return 0;
    }
    
    result test(int a,double b)
    {
    struct result ret;
    ret.first = a;
    ret.second = b;
    return ret;
    }

    输出

    1
    2.1234

    demo3
    c++ 使用结构体作为返回值

    #include <stdio.h>
    typedef struct {
    int a;
    int b;
    }Stu;
    Stu getStu(int x, int y)
    {
    Stu result;
    result.a = x;
    result.b = y;
    return result;
    }
    int main()
    {
    int a = 2, b = 3;
    Stu test = getStu(a, b);
    printf("%d %d
    ", test.a, test.b);
    return 0;
    }

    输出

    2 3


    demo4
    c++ 使用结构体指针作为返回值

    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct {
    int a;
    int b;
    }Stu;
    
    Stu* getStu(int x, int y)
    {
    Stu* pStu = (Stu*)malloc(sizeof(Stu));
    pStu->a = x;
    pStu->b = y;
    return pStu;
    }
    
    int main()
    {
    int x = 2, y = 3;
    Stu *pStu = getStu(x, y);
    printf("%d %d
    ", pStu->a, pStu->b);
    free(pStu);
    return 0;
    }

    输出

    2 3

    参考:

    https://blog.csdn.net/chaipp0607/article/details/64124704/

    https://blog.csdn.net/dfq12345/article/details/73924580

  • 相关阅读:
    【PHP学习】PHP 变量
    【PHP学习】PHP 语法
    枚举进程使用的DLL
    多线程学习----CreateThread
    C++接口定义及实现举例
    注册表操作(VC_Win32)
    Windows 动态链接库编程
    [代码]JAVA触发器,Spring的quartz配置
    [实例]JAVA调用微信接口发送图文消息,不用跳到详情页
    [实例]JAVA生成字母+随机数字并生成文件
  • 原文地址:https://www.cnblogs.com/sea-stream/p/11129961.html
Copyright © 2011-2022 走看看