日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

函数||值传递||函数的常见样式||函数的声明||函数的分文件编写

發(fā)布時(shí)間:2025/4/16 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 函数||值传递||函数的常见样式||函数的声明||函数的分文件编写 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

概述

作用:將一段經(jīng)常使用的代碼封裝起來(lái),減少重復(fù)代碼

一個(gè)較大的程序,一般分為若干個(gè)程序塊,每個(gè)模塊實(shí)現(xiàn)特定的功能。


函數(shù)的定義

函數(shù)的定義一般主要有5個(gè)步驟:

1、返回值類(lèi)型

2、函數(shù)名

3、參數(shù)表列

4、函數(shù)體語(yǔ)句

5、return 表達(dá)式

#include <iostream> using namespace std; //函數(shù)定義 int add(int num1, int num2) //定義中的num1,num2稱(chēng)為形式參數(shù),簡(jiǎn)稱(chēng)形參 {int sum = num1 + num2;return sum; }int main() {int a = 10;int b = 10;//調(diào)用add函數(shù)int sum = add(a, b);//調(diào)用時(shí)的a,b稱(chēng)為實(shí)際參數(shù),簡(jiǎn)稱(chēng)實(shí)參cout << "sum = " << sum << endl;a = 100;b = 100;sum = add(a, b);cout << "sum = " << sum << endl;system("pause");return 0; }



值傳遞

#include <iostream> using namespace std; void swap(int num1, int num2) {cout << "交換前:" << endl;cout << "num1 = " << num1 << endl;cout << "num2 = " << num2 << endl;int temp = num1;num1 = num2;num2 = temp;cout << "交換后:" << endl;cout << "num1 = " << num1 << endl;cout << "num2 = " << num2 << endl;//return ; 當(dāng)函數(shù)聲明時(shí)候,不需要返回值,可以不寫(xiě)return }int main() {int a = 10;int b = 20;swap(a, b);cout << "mian中的 a = " << a << endl;cout << "mian中的 b = " << b << endl;system("pause");return 0; }



函數(shù)的常見(jiàn)樣式

常見(jiàn)的函數(shù)樣式有4種

  • 無(wú)參無(wú)返

  • 有參無(wú)返

  • 無(wú)參有返

  • 有參有返

  • //函數(shù)常見(jiàn)樣式 //1、 無(wú)參無(wú)返 void test01() {//void a = 10; //無(wú)類(lèi)型不可以創(chuàng)建變量,原因無(wú)法分配內(nèi)存cout << "this is test01" << endl;//test01(); 函數(shù)調(diào)用 }//2、 有參無(wú)返 void test02(int a) {cout << "this is test02" << endl;cout << "a = " << a << endl; }//3、無(wú)參有返 int test03() {cout << "this is test03 " << endl;return 10; }//4、有參有返 int test04(int a, int b) {cout << "this is test04 " << endl;int sum = a + b;return sum; }

    函數(shù)的聲明

    作用: 告訴編譯器函數(shù)名稱(chēng)及如何調(diào)用函數(shù)。函數(shù)的實(shí)際主體可以單獨(dú)定義。

    • 函數(shù)的聲明可以多次,但是函數(shù)的定義只能有一次

    #include <iostream> using namespace std; //聲明可以多次,定義只能一次 //聲明 int max(int a, int b); int max(int a, int b); //定義 int max(int a, int b) {return a > b ? a : b; }int main() {int a = 100;int b = 200;cout << max(a, b) << endl;system("pause");return 0; }

    ?



    函數(shù)的分文件編寫(xiě)

    作用:讓代碼結(jié)構(gòu)更加清晰

    函數(shù)分文件編寫(xiě)一般有4個(gè)步驟

  • 創(chuàng)建后綴名為.h的頭文件

  • 創(chuàng)建后綴名為.cpp的源文件

  • 在頭文件中寫(xiě)函數(shù)的聲明

  • 在源文件中寫(xiě)函數(shù)的定義

  • ?

    總結(jié)

    以上是生活随笔為你收集整理的函数||值传递||函数的常见样式||函数的声明||函数的分文件编写的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

    如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。