4124人加入学习
(13人评价)
C++编程系列 第二季函数和类

制作于2018.4.2

价格 免费

函数指针

与数据项类似,函数也有地址。函数的地址是存储其机器语言代码内存的开始地址。可以将地址作为函数的参数,从而使第一个函数能够找到第二个函数,并运行它。

函数指针指向的是函数而非对象。

想要声明一个可以指向函数的指针,只需要用指针替换函数名即可。

bool lengthCompare(const string &,const string &); //函数

bool (*pf)(const string &,const string &); //函数指针

 

函数指针

bool (*pf)(const string &,const string &);

pf是一个指向函数的指针,其中该函数的参数是两个const string 的引用,返回值是布尔类型。

注意:*pf两端的括号必不可少,如果省略括号,就变成了一个返回值为bool指针的函数,而不是指向函数的指针

当我们把函数名作为一个值使用时,该函数自动地转换成指针。还可以直接使用指向函数的指针调用该函数

 

#include <iostream>
#include <string>

using namespace std;

bool lengthCompare(const string &s1, const string &s2);
void display(const string &s1, const string&s2, bool(*p)(const string &, const string &));

int main()
{
	string name1 = "Sandy";
	string name2 = "Jane";
	
	//bool res = lengthCompare(name1, name2);

	//定义一个函数指针并给它赋值,pf是指向函数lengthCompare的指针
	bool(*pf)(const string &, const string &);
	pf = lengthCompare;
	/*res = pf(name1, name2);
	if (res == true)
	{
		cout << name1 << "的长度大于" << name2 << endl;
	}
	else
	{
		cout << name1 << "的长度小于" << name2 << endl;
	}*/

	//将pf作为实参传递给函数display
	display(name1, name2, pf);
	return 0;
}

//对比两个字符串的长度
bool lengthCompare(const string &s1, const string &s2)
{
	return size(s1) > size(s2) ? true : false;
}

//将函数指针作为参数传递给另外一个函数,可以直接在这个函数中通过函数指针指向的函数
void display(const string &s1, const string&s2, bool(*p)(const string &, const string &))
{
	if (p(s1, s2) == true)
	{
		cout << s1 << "的长度大于" << s2 << endl;
	}
	else
	{
		cout << s1 << "的长度小于" << s2 << endl;
	}
}

[展开全文]

分离式编译

随着程序越来越复杂,我们希望把程序的各个部分分别存储在不同的文件中。

我们可以将原来的程序分成三个部分:

1.头文件:包含结构声明和使用这些结构的函数的原型。

2.源代码文件:包含于结构有关的函数的代码。

3.源代码文件:包含调用与结构相关的函数的代码。

 

2 :函数定义

3:使用

 

分离式编译

头文件中常包含的内容:

1.函数原型

2.使用#define或const定义的符号常量

3.结构声明

4.类声明

5.模板声明

6.内联函数

 

//game.h

#pragma once

#ifndef GAME_H_
#define GAME_H_

#include <string>
using namespace std;

struct Game
{
	string gameName;
	float gameScore;
};

void inputGame(Game games[],const int size);
void sort(Game games[],const  int size);
void display(const Game games[],const int size);

const int Size = 5;

#endif // !GAME_H_

//game.cpp

#include "game.h"
#include <iostream>

void inputGame(Game games[], const int size)
{
	for (int i = 0; i < size; i++)
	{
		cout << "请输入喜爱的游戏的名称:";
		cin >> games[i].gameName;
		cout << "请输入游戏评分(10以内的小数):";
		cin >> games[i].gameScore;
	}
}

void sort(Game games[], const  int size)
{
	Game temp;
	for (int i = 0; i < size - 1; i++)
	{
		for (int j = i + 1; j < size; j++)
		{
			if (games[i].gameScore < games[j].gameScore)
			{
				temp = games[i];
				games[i] = games[j];
				games[j] = temp;
			}
		}
	}
}

void display(const Game games[], const int size)
{
	for (int i = 0; i < size; i++)
	{
		cout << i + 1 << ":" << games[i].gameName << "(" << games[i].gameScore << ")" << endl;
	}
}

//17分离式编译.cpp

#include "game.h"
#include <iostream>

int main()
{
	cout << "请输入5个你喜爱的游戏的名称,并给它们评分:" << endl;
	Game games[Size] = {};
	inputGame(games, Size);
	sort(games, Size);
	display(games, Size);
	return 0;
}

 

习题4

完成程序:药品物资管理

要求:

1.利用结构体来存储目前拥有的药物的名称、种类、数量、买入价格、卖出价格。

2.利用枚举来设置药物的种类(回复mp和回复hp)。

3.编写函数来控制药物的买入和卖出,卖出价为买入价格的3/4。

4.编写函数来显示拥有的药物的剩余钱数。

5.通过输入数字来控制函数调用。

6.实现分离式编译。

 

[展开全文]

习题4

完成程序:药品物资管理

要求:

1.利用结构体来存储目前拥有的药物的名称、种类、数量、买入价格、卖出价格。

2.利用枚举来设置药物的种类(回复mp和回复hp)。

3.编写函数来控制药物的买入和卖出,卖出价为买入价格的3/4。

4.编写函数来显示拥有的药物的剩余钱数。

5.通过输入数字来控制函数调用。

6.实现分离式编译。

 

//drug.h

#pragma once
#ifndef DRUG_H_
#define DRUG_H_
#include <string>

using namespace std;

enum Type {PlusHP,PlusMP};

struct Drug
{
	string name;
	Type type;
	int count;
	float buyPrice;
	float sellPrice;
};

void buyDrug(Drug &d, float& money, int num);
void sellDrug(Drug &d, float&money, int num);
void display(const Drug &d1, const Drug &d2, const float money);
string showType(const Drug &d);

#endif // !DRUG_H_

//drug.cpp

#include "pch.h"
#include "drug.h"
#include <iostream>

void buyDrug(Drug &d, float& money, int num)
{
	if (money > d.buyPrice * num)
	{
		money -= d.buyPrice*num;
		d.count += num;
		cout << "购买成功!" << endl;
	}
	else
	{
		cout << "警告:拥有的钱不足够购买" << num << "个药品!!!" << endl;
	}
}

void sellDrug(Drug &d, float&money, int num)
{
	if (d.count >= num)
	{
		d.count -= num;
		money += d.sellPrice * num;
		cout << "卖出成功!" << endl;
	}
	else
	{
		cout << "警告:没有" << num << "个药物可以售卖!!!" << endl;
	}
}

void display(const Drug &d1, const Drug &d2, const float money)
{
	cout << "目前拥有的药物:" << endl;
	cout << "1:名称:" << d1.name << "  数量:" << d1.count << "  种类:" << showType(d1) << "  购入价格:" << d1.buyPrice << "  卖出价格:" << d1.sellPrice << endl;
	cout << "1:名称:" << d2.name << "  数量:" << d2.count << "  种类:" << showType(d2) << "  购入价格:" << d2.buyPrice << "  卖出价格:" << d2.sellPrice << endl;
	cout << "拥有钱数:" << money << endl;
	cout << "显示完成!" << endl;
}

string showType(const Drug &d)
{
	switch (d.type)
	{
	case 0:
		return "PlusHP";
		break;
	case 1:
		return "PlusMP";
		break;
	default:
		break;
	}
}

 

[展开全文]

习题4

完成程序:药品物资管理

要求:

1.利用结构体来存储目前拥有的药物的名称、种类、数量、买入价格、卖出价格。

2.利用枚举来设置药物的种类(回复mp和回复hp)。

3.编写函数来控制药物的买入和卖出,卖出价为买入价格的3/4。

4.编写函数来显示拥有的药物的剩余钱数。

5.通过输入数字来控制函数调用。

6.实现分离式编译。

 

//drug.h

#pragma once
#ifndef DRUG_H_
#define DRUG_H_
#include <string>

using namespace std;

enum Type {PlusHP,PlusMP};

struct Drug
{
	string name;
	Type type;
	int count;
	float buyPrice;
	float sellPrice;
};

const float ratio = 0.75f;
constexpr float sellPrice(Drug &d) { return d.buyPrice*ratio; }

void buyDrug(Drug &d, float& money, int num);
void sellDrug(Drug &d, float&money, int num);
void display(const Drug &d1, const Drug &d2, const float money);
string showType(const Drug &d);

#endif // !DRUG_H_

//drug.cpp

#include "pch.h"
#include "drug.h"
#include <iostream>

void buyDrug(Drug &d, float& money, int num)
{
	if (money > d.buyPrice * num)
	{
		money -= d.buyPrice*num;
		d.count += num;
		cout << "购买成功!" << endl;
	}
	else
	{
		cout << "警告:拥有的钱不足够购买" << num << "个药品!!!" << endl;
	}
}

void sellDrug(Drug &d, float&money, int num)
{
	if (d.count >= num)
	{
		d.count -= num;
		money += d.sellPrice * num;
		cout << "卖出成功!" << endl;
	}
	else
	{
		cout << "警告:没有" << num << "个药物可以售卖!!!" << endl;
	}
}

void display(const Drug &d1, const Drug &d2, const float money)
{
	cout << "目前拥有的药物:" << endl;
	cout << "1:名称:" << d1.name << "  数量:" << d1.count << "  种类:" << showType(d1) << "  购入价格:" << d1.buyPrice << "  卖出价格:" << d1.sellPrice << endl;
	cout << "1:名称:" << d2.name << "  数量:" << d2.count << "  种类:" << showType(d2) << "  购入价格:" << d2.buyPrice << "  卖出价格:" << d2.sellPrice << endl;
	cout << "拥有钱数:" << money << endl;
	cout << "显示完成!" << endl;
}

string showType(const Drug &d)
{
	switch (d.type)
	{
	case 0:
		return "PlusHP";
		break;
	case 1:
		return "PlusMP";
		break;
	default:
		break;
	}
}

//习题4.cpp

#include "pch.h"
#include "drug.h"
#include <iostream>

int main()
{
	Drug mpDrug = { "回魔药水",PlusMP,10,150,sellPrice(mpDrug) };
	Drug hpDrug = { "回血药水",PlusHP,20,100,sellPrice(hpDrug) };
	float totalMoney = 1000;

	cout << "1:购买回血药品 / 2:购买回魔药品 / 3:卖出回血药品 / 4:卖出回魔药品 / 5:输出目前拥有的药水和金钱 / 6:退出" << endl;
	cout << "请输入操作:" << endl;
	int input = 0;
	int num = 0;
	while (cin >> input && input > 0 && input < 6)
	{
		if (input == 1)
		{
			cout << "请输入购买数量:" << endl;
			if (cin >> num && num > 0)
			{
				buyDrug(hpDrug, totalMoney, num);
				cout << "请继续输入操作:" << endl;
			}
			else
			{
				cout << "输入错误,请重新输入:" << endl;
			}
		}
		else if (input == 2)
		{
			cout << "请输入购买数量:" << endl;
			if (cin >> num && num > 0)
			{
				buyDrug(mpDrug, totalMoney, num);
				cout << "请继续输入操作:" << endl;
			}
			else
			{
				cout << "输入错误,请重新输入:" << endl;
			}
		}
		else if (input == 3)
		{
			cout << "请输入卖出数量:" << endl;
			if (cin >> num && num > 0)
			{
				sellDrug(hpDrug, totalMoney, num);
				cout << "请继续输入操作:" << endl;
			}
			else
			{
				cout << "输入错误,请重新输入:" << endl;
			}
		}
		else if (input == 4)
		{
			cout << "请输入卖出数量:" << endl;
			if (cin >> num && num > 0)
			{
				sellDrug(mpDrug, totalMoney, num);
				cout << "请继续输入操作:" << endl;
			}
			else
			{
				cout << "输入错误,请重新输入:" << endl;
			}
		}
		else
		{
			display(hpDrug, mpDrug, totalMoney);
			cout << "请继续输入操作:" << endl;
		}
	}
	
	return 0;
}

 

 

 

 

 

//自写:

//Medicine.h

#pragma once
#ifndef MEDICINE_H_
#define MEDICINE_H_
#include <iostream>
#include <string>

using namespace std;

enum Sort :short
{
	PlusHP=0,
	PlusMP=1
};

struct Medicine
{
	string name;
	int count; 
	Sort sort;
	float buying_price;
	float selling_price;
};

void BuyMedicine(Medicine& med, float& money);
void SellMedicine(Medicine& med, float& money);
void DisplayAllMedicineAndMoney(Medicine med1,Medicine med2, const float money);

#endif // !MEDICINE_H_

//Medicine.cpp

#include"pch.h"
#include "Medicine.h"

void BuyMedicine(Medicine& med, float& money)
{
	int buyCount;
	cout << "请输入购买数量:" << endl;
	cin >> buyCount;

	float totalPrice = buyCount * med.buying_price;
	if (totalPrice < money && buyCount > 0)
	{
		money -= totalPrice;
		med.count += buyCount;
		cout << "购买成功!" << endl;
	}
	else
	{
		cout << "购买失败" << endl;
	}
}

void SellMedicine(Medicine& med, float& money)
{
	int sellCount;
	cout << "请输入卖出数量:" << endl;
	cin >> sellCount;

	if (med.count >= sellCount && sellCount > 0)
	{
		money += sellCount * med.selling_price;
		med.count -= sellCount;
		cout << "卖出成功!" << endl;
	}
	else
	{
		cout << "卖出失败" << endl;
	}
}

void DisplayAllMedicineAndMoney(Medicine med1, Medicine med2, const float money)
{
	cout << "目前拥有的药品:" << endl;
	cout << "1:名称:" << med1.name << "  数量:" << med1.count << "  种类:" << (med1.sort == 0 ? "PlusHP" : "PlusMP") << "  购入价格:" << med1.buying_price << "  卖出价格:" << med1.selling_price << endl;
	cout << "2:名称:" << med2.name << "  数量:" << med2.count << "  种类:" << (med2.sort == 1 ? "PlusMP" : "PlusHP") << "  购入价格:" << med2.buying_price << "  卖出价格:" << med2.selling_price << endl;
	cout << "拥有钱数:" << money << endl;
	cout << "显示完成!" << endl;
}

//习题4.cpp

#include "pch.h"
#include "Medicine.h"

int main()
{
	Medicine HP_Return = { "回血药水",20,PlusHP,100,75 };
	Medicine MP_Return = { "回魔药水",10,PlusMP,150,112.5 };
	float money = 1000.0f;

	cout << "1.购买回血药品 / 2.购买回魔药品 / 3.卖出回血药品 / 4.卖出回魔药品 / 5.输出目前拥有的药水和金钱 / 6.退出" << endl;
	bool isContinue = true;
	int inputNum;
	while (isContinue)
	{
		cout << "请输入操作:" << endl;
		cin >> inputNum;
		switch (inputNum)
		{
		case 1:
			BuyMedicine(HP_Return, money);
			break;
		case 2:
			BuyMedicine(MP_Return, money);
			break;
		case 3:
			SellMedicine(HP_Return, money);
			break;
		case 4:
			SellMedicine(MP_Return, money);
			break;
		case 5:
			DisplayAllMedicineAndMoney(HP_Return, MP_Return, money);
			break;
		case 6:
			isContinue = false;
			break;
		default:
			break;
		}
	}
}

 

[展开全文]

辅助学习顶层const、底层const

https://www.bilibili.com/video/BV1xY411t75L

[展开全文]

可以用static关键字来修饰局部变量,从而获取局部静态对象。

static int cout==0;

[展开全文]

形参的类型决定了形参和实参的

[展开全文]

int n=0

int &r=n(&不再是地址运算符,r是n)

[展开全文]

在原本声明函数原型的地方加上inline

[展开全文]
01RK · 2021-03-21 · 113-内联函数 0
#include <iostream>

using namespace std;

int main(){
    cout << "Hello world!" << endl;
    return 0;
}
[展开全文]

注意指针做形参的时候,可能会把指针所指的值修改掉。

[展开全文]

过程性编程和面向对象编程

过程性编程:就是分析出解决问题所需要的步骤,然后用函数把这些步骤一步一步实现,使用的时候一个一个依次调用。

面向对象编程:就是把构成问题事务分解成各个对象,建立对象的目的不是为了完成一个步骤,而是为了描叙某个事物在整个解决问题的步骤中的行为。

 

采用过程性编程方法时,首先考虑要遵循的步骤,然后考虑如何表示这些数据。

采用面向对象编程(OOP)的方法时,首先从用户的角度考虑对象,描述对象所需的数据以及描述用户与数据交互所需要的操作。完成对接口的描述后,需要确定如何实现接口和数据存储。最后,使用新的设计方案创建出程序。

 

面向对象编程

面向对象编程的特性:

1.抽象

2.封装和数据隐藏

3.多态

4.继承

5.代码的可重用性

为了实现这些特性并将它们组合在一起,C++所作的最重要的改进是提供了

 

[展开全文]

类的定义

类的基本思想是数据抽象和封装

抽象:对具体对象或问题进行概括,抽出这一类对象的公共性质并加以描述的过程。

数据抽象是一种依赖于接口和实现分离的编程技术。

类的接口包括用户所能执行的操作;类的实现则包括类的数据成员、负责接口实现的函数体以及定义所需的各种私有函数。

 

封装:将抽象出的数据成员、行为成员相结合,将他们视为一个整体——类。

封装实现了类的接口和实现的分离。封装后的类隐藏了它的实现细节,也就是说,类的用户只能使用接口而无法访问实现部分。

 

类声明

一般来说,类由两个部分组成:

1.类声明:以成员数据的方式描述数据部分,以成员函数(方法)的方式描述公有接口。

2.类方法定义:描述如何实现类成员函数。

通常,我们在接口放在头文件(.h)中,并将实现放在源代码文件(.cpp)中。

private:标识只能通过公共成员访问的类成员(数据隐藏),不能被使用该类的代码访问。

public:标识组成类的公共接口的类成员(抽象),在整个程序内可被访问。

公共成员函数是程序和对象的私有成员之间的桥梁,提供了对象和程序之间的接口,同时私有成员防止了程序直接访问数据。

[展开全文]

内联函数

inline + 调用函数(不支持递归)

inline int res ( inta, intb)

{

return a+b;

}

主函数

[展开全文]

//student.h

#pragma once

#ifndef STUDENT_H_
#define STDENT_H_

#include <iostream>
#include <string>

using namespace std;

//class关键字和类名
class Student
{
	//私有成员,定义数据成员,只能通过公有接口进行访问,数据隐藏
private:
	string name;
	int chinese;
	int math;
	int english;

	//共有接口
public:
	void setStudent(string name, int chinese, int math, int english);
	int sum(const Student &s);
	float avery(const Student &s);
	bool pass(const Student &s);
};

#endif // !STUDENT_H_

 

[展开全文]

函数与数组

数据作为参数时:
int my (const int money[ ], int n) //指针

{

for (int i=0; i<n; i++)

{

 int res+=money [i];//数组

}

return res;

int main

{

int qian[]={143,562,5,};

int s =my(qian, n)//指针

}

[展开全文]

    const int size = 5;

    Food foods[size] = {};
    

    cout << "请输入你喜欢的" << size << "个食物,并给它们打分。(分数为0-10之间的小数)"<<endl;
    cout << "请输入你喜欢的食物的名称:" << endl;
    for (int i = 0; i < size; i++) {

        cin >> foods[i].foodName;
        cout << "请给你喜欢的食物打分:" << endl;
        cin >> foods[i].foodScore;
       
        if (foods[i].foodScore < 0 || foods[i].foodScore > 10)  {
            cout << "Warning! 分数超出范围!" << endl << "请重新输入第" << i + 1 << "个食物的名称:" << endl;
            i--;
            
        }
        else if(i<size-1){
            cout << "请输入第" << i + 2 << "个食物的名称:" << endl;
        }
    }

        for (/*i = 0*/int i = 0; /*i < size;*/i < size-1; i++) {
            for (int j = i + 1; j < size; j++) {
                Food temp;
                if (foods[i].foodScore < foods[j].foodScore) {
                    temp = foods[i];
                    foods[i] = foods[j];
                    foods[j] = temp;
                }
            }
        }
    //                     i =  0 1 2 3     (i+1)j =  1 2 3 4
   

        cout << "排名:食物名称(分数)" << endl;

        for (int i = 0; i < size; i++) {
            cout << i + 1 << ":" << foods[i].foodName << "(" << foods[i].foodScore << ")" << endl;
        }

[展开全文]
陆浅 · 2020-08-03 · 006-习题1 0

授课教师

SIKI学院老师

课程特色

下载资料(1)
视频(43)