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, ); ... }
  • 相关阅读:
    [转]经典SQL语句大全
    【转】windows 7系统安装与配置Tomcat服务器环境
    [转]php连接postgresql
    win7(64位)php5.5-Apache2.4-环境安装
    [转]WIN7系统安装Apache 提示msvcr110.DLL
    【转】如何在CentOS/RHEL中安装基于Web的监控系统 linux-das
    CentOS6.5安全策略设置
    【转】Lua编程规范
    在python中的使用
    游标 cursor
  • 原文地址:https://www.cnblogs.com/haijian/p/13062587.html
Copyright © 2011-2022 走看看