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

相关推荐
laimaxgg1 分钟前
五、central cache的设计
c++·缓存·性能优化
chenyuhao20248 分钟前
链表面试题9之环形链表进阶
数据结构·算法·链表·面试·c#
炯哈哈24 分钟前
【上位机——WPF】命名空间
开发语言·windows·c#·wpf·上位机
chenyuhao202439 分钟前
链表的面试题8之环形链表
数据结构·算法·链表·面试·c#
Yan_ks1 小时前
JAVA面向对象——对象和类的基本语法
java·开发语言
虾球xz1 小时前
游戏引擎学习第289天:将视觉表现与实体类型解耦
c++·学习·游戏引擎
Panesle1 小时前
Index-AniSora模型论文速读:基于人工反馈的动漫视频生成
人工智能·算法·机器学习·计算机视觉·开源·大模型·生成模型
Paddy哥1 小时前
jsmpeg+java+ffmpeg 调用摄像头RTSP流播放
java·开发语言·ffmpeg
liuzhangfeiabc1 小时前
[luogu12542] [APIO2025] 排列游戏 - 交互 - 博弈 - 分类讨论 - 构造
c++·算法·题解