zoukankan      html  css  js  c++  java
  • C++基础学习(三)之函数

    函数的基本结构

    Return_type Function_name(parameter list)
    {
        body of the function
    }

    函数声明

    #include<iostream>
    void main()
    {
        void function(int a, int b);  //函数声明1
        //void function(int, int);  //函数声明2
        ...
        int x = 15, y = 20;
        function(x, y);  //函数调用,x、y为实参(实际参数)
    }
    void function(int a, int b)  //a、b为形参(形式参数)
    {
        ...
    }

    多文件(.cpp)之间的函数调用

    1 利用函数声明

    在主文件中直接进行声明即可,无需添加“function.cpp”源文件,否则报错;

    //function.cpp
    #include<iostream> void function() { ... }
    //main.cpp
    #include<iostream>
    void function();  //函数声明
    void main()
    {
        ...
        function();  //函数调用
        ...
    }

    2 利用头文件

    在主文件中添加头文件“function.h”即可,无需声明函数;

    //function.h
    #include<iostream>
    void function();
    //function.cpp
    #include"function.h"
    void function()
    {
        ...
    }
    //main.cpp
    #include<iostream>
    #include"function.h"
    void main()
    {
        ...
        function();  //函数调用
        ...
    }

    函数参数传递

    0 传值调用

    值传递,形参不影响实参;

    1 指针调用

    #include<iostream>
    using namespace std;
    void swap(int *x, int *y) //参数互换 { int temp; temp = x; x = y; y = temp; } int main() { int a = 10, b = 20; cout << a << endl << b << endl; swap(&a, &b); cout << a << endl << b << endl; return 0; }

    2 引用调用

    #include<iostream>
    using namespace std;
    void swap(int &x, int &y) //参数互换 { int temp; temp = x; x = y; y = temp; } int main() { int a = 10, b = 20; cout << a << endl << b << endl; swap(a, b); cout << a << endl << b << endl; return 0; }

    默认参数

    #include<iostream>
    
    int function(int a, int b = 10)  //形参b赋予默认值10,如果函数调用过程中实参为空,则使用默认参数10
    {
        ...
    }
    int main() { ... function(x, y); function(x, ); ... }
  • 相关阅读:
    基于CentOS7配置ArcGIS enterprise
    ArcGIS pro 发布地图服务(一)动态地图服务
    ArcGIS操作技巧——怎样把地图放到PPT中,并且进行编辑?
    ArcGIS Earth1.9最新版安装和使用教程
    ArcGIS pro2.3中添加天地图底图
    excle函数
    网闸和防火墙
    NoSQL——not onlySQL不仅仅是SQL
    leaflet学习一 入门
    openlayer3 基础学习一创建&显示地图
  • 原文地址:https://www.cnblogs.com/haijian/p/13062587.html
Copyright © 2011-2022 走看看