函数的总结1

1.函数的定义

class 函数名(){

表达式

};`

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

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

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值