函数的总结1

1.函数的定义

class 函数名(){

表达式

};`

####2.函数的四种形式

c++ 复制代码
#include <iostream>
#include <string>

using namespace std;


// 无参无返回值
void setHi() {
	cout << "你好···" << endl;
}

// 无参有返回值
string saySorry() {
	return "对不起了。。。";
}

// 有参无返回值
void printIN(string name) {
	cout << "我的名字是:" << name << endl;
}

// 有参有返回值
string getMsg(string msg) {
	return "我的消息是:" + msg;
}


int main() {

	setHi();
	cout << saySorry() << endl;
	printIN("小明");
	cout << getMsg("你好") << endl;

	return 0;
}
3.分离式编程
复制代码
// stu3.h

#pragma once
//#include <iostream>
#include <string>

using namespace std;

void setHi();

string saySorry();

void printIN(string name);


string getMsg(string msg);
  • stu3.cpp

    复制代码
    #include <iostream>
    #include "stu3.h"
    
    using namespace std;
    
    
    // 无参无返回值
    void setHi() {
    	cout << "你好···" << endl;
    }
    
    // 无参有返回值
    string saySorry() {
    	return "对不起了。。。";
    }
    
    // 有参无返回值
    void printIN(string name) {
    	cout << "我的名字是:" << name << endl;
    }
    
    // 有参有返回值
    string getMsg(string msg) {
    	return "我的消息是:" + msg;
    }
  • function.cpp

    复制代码
    #include <iostream>
    #include <string>
    #include "stu3.h"
    
    
    
    int main() {
    
    	setHi();
    	cout << saySorry() << endl;
    	printIN("小明");
    	cout << getMsg("你好") << endl;
    
    	return 0;
    }
    4.函数重载
    复制代码
    #include <iostream>
    
    using namespace std;
    
    int add(int a,int b) {
    	return a + b;
    }
    
    int add(int a, int b, int c) {
    	return a + b + c;
    }
    
    int add(double a, int b) {
    	return a + b;
    }
    
    int add(int a, double b) {
    	return a + b;
    }
    
    int main() {
    	cout << add(1, 3) << endl;
    	cout << add(1, 2, 3) << endl;
    	cout << add(1.2, 3) << endl;
    	cout << add(1, 1.2) << endl;
    }
    • 重载的分类:
      • 参数的个数不同
      • 参数的传参类型不同
      • 参数的传参类型顺序不同

相关推荐
Mallow Flowers32 分钟前
Python训练营-Day31-文件的拆分和使用
开发语言·人工智能·python·算法·机器学习
云边小网安1 小时前
java集合篇(六) ---- ListIterator 接口
java·开发语言·青少年编程·java集合
不被定义的程序猿1 小时前
Golang 在 Linux 平台上的并发控制
开发语言·后端·golang
GalaxyPokemon1 小时前
LeetCode - 704. 二分查找
数据结构·算法·leetcode
leo__5202 小时前
matlab实现非线性Granger因果检验
人工智能·算法·matlab
GG不是gg2 小时前
位运算详解之异或运算的奇妙操作
算法
陈旭金-小金子2 小时前
发现 Kotlin MultiPlatform 的一点小变化
android·开发语言·kotlin
呃m2 小时前
双重特征c++
c++
Mikhail_G2 小时前
Python应用八股文
大数据·运维·开发语言·python·数据分析
景彡先生2 小时前
C++ 中文件 IO 操作详解
开发语言·c++