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

相关推荐
雪域迷影13 分钟前
C#中通过get请求获取api.open-meteo.com网站的天气数据
开发语言·http·c#·get
yue00814 分钟前
C#类继承
java·开发语言·c#
Want59521 分钟前
Python汤姆猫
开发语言·python
Larry_Yanan43 分钟前
QML学习笔记(五十)QML与C++交互:QML中单例C++对象
开发语言·c++·笔记·qt·学习·ui·交互
im_AMBER44 分钟前
算法笔记 09
c语言·数据结构·c++·笔记·学习·算法·排序算法
凯芸呢1 小时前
Java中的数组(续)
java·开发语言·数据结构·算法·青少年编程·排序算法·idea
竹竹零1 小时前
JacksonUtil--序列化与反序列化
java·开发语言·windows
寂静山林1 小时前
UVa 1030 Image Is Everything
算法
AI柠檬1 小时前
几种排序算法的实现和性能比较
数据结构·算法·c#·排序算法
sheji34161 小时前
【开题答辩全过程】以 基于Java的旅游网站的设计与开发为例,包含答辩的问题和答案
java·开发语言·旅游