函数的总结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;
    }
    • 重载的分类:
      • 参数的个数不同
      • 参数的传参类型不同
      • 参数的传参类型顺序不同

相关推荐
AKDreamer_HeXY5 分钟前
ABC434E 题解
c++·算法·图论·atcoder
罗湖老棍子5 分钟前
完全背包 vs 多重背包的优化逻辑
c++·算法·动态规划·背包
TL滕6 分钟前
从0开始学算法——第四天(题目参考答案)
数据结构·笔记·python·学习·算法
二川bro6 分钟前
循环性能提升:Python向量化计算技巧
开发语言·python
TracyCoder12311 分钟前
大白话讲Java NIO
java·开发语言·nio
potato_may16 分钟前
C++ 发展简史与核心语法入门
开发语言·c++·算法
Liangwei Lin18 分钟前
洛谷 P1443 马的遍历
数据结构·算法
老鱼说AI20 分钟前
算法基础教学第二步:数组(超级详细原理级别讲解)
数据结构·神经网络·算法·链表
m5655bj21 分钟前
通过 C# 将 RTF 文档转换为图片
开发语言·c#