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

相关推荐
lqjun082717 小时前
Qt程序单独运行报错问题
开发语言·qt
hdsoft_huge19 小时前
Java & Spring Boot常见异常全解析:原因、危害、处理与防范
java·开发语言·spring boot
风中的微尘19 小时前
39.网络流入门
开发语言·网络·c++·算法
未来之窗软件服务20 小时前
幽冥大陆(二)RDIFSDK 接口文档:布草洗涤厂高效运营的技术桥梁C#—东方仙盟
开发语言·c#·rdif·仙盟创梦ide·东方仙盟
混分巨兽龙某某20 小时前
基于Qt Creator的Serial Port串口调试助手项目(代码开源)
c++·qt creator·串口助手·serial port
西红柿维生素20 小时前
JVM相关总结
java·jvm·算法
小冯记录编程20 小时前
C++指针陷阱:高效背后的致命危险
开发语言·c++·visual studio
1uther21 小时前
Unity核心概念⑨:Screen
开发语言·游戏·unity·c#·游戏引擎
C_Liu_21 小时前
C++:类和对象(下)
开发语言·c++
coderxiaohan21 小时前
【C++】类和对象1
java·开发语言·c++