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

制作于2018.4.2

价格 免费

类型前加Friend......

么怎么用过直接publick生成一个函数引用.....

[展开全文]

 

友元函数

类可以允许其他类或者函数访问它的非公有成员,方法是令其他类或者函数成为它的友元(friend)。

如果类想把一个函数作为它的友元,只需要增加一条以friend关键字开始的函数声明语句即可:

friend void printMath(Student &s);

注意:友元函数不是类的成员函数,友元函数不能直接访问类的成员,只能通过对象访问。

 

//student.h

#pragma once

#ifndef STUDENT_H_
#define STDENT_H_

#include <iostream>
#include <string>

using namespace std;

//class关键字和类名
class Student
{
	//Student类的友元函数,但是不是这个类的函数成员
	friend void printMath(Student &s);
	//私有成员,定义数据成员,只能通过公有接口进行访问,数据隐藏
private:
	string name_;
	int chinese_;
	int math_;
	int english_;
	static const int PassingScore = 60;
	//公有接口
public:
	Student(string name, int chinese, int math, int english);
	Student();
	~Student();
	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_

 

//student.cpp

#include "pch.h"
#include "student.h"

Student::Student(string name, int chinese, int math, int english)
{
	name_ = name;
	chinese_ = chinese;
	math_ = math;
	english_ = english;
}

Student::Student()
{
}

Student::~Student()
{
}

void Student::setStudent(string name, int chinese, int math, int english)
{
	name_ = name;
	chinese_ = chinese;
	math_ = math;
	english_ = english;
}

int Student::sum(const Student & s)
{
	return s.chinese_+s.math_ +s.english_;
}

float Student::avery(const Student & s)
{
	return(float)(s.chinese_ + s.math_ + s.english_) / 3;
}

bool Student::pass(const Student & s)
{
	if (s.chinese_ >= PassingScore && s.math_ >= PassingScore && s.english_ >= PassingScore)
	{
		return true;
	}
	else
	{
		return false;
	}
}

void printMath(Student & s)
{
	cout << "数学成绩为:" << s.math_ << endl;
}

//18-类的定义.cpp

#include "pch.h"
#include "student.h"

int main()
{
	//通过构造函数显示的初始化和隐式的初始化
	Student stu1 = Student("Sandy", 50, 120, 110);
	Student stu2("Jane", 110, 90, 100);
	Student stu3;
	/*string name1 = "Sandy";
	int chinese1 = 100;
	int math1 = 120;
	int english1 = 110;
	stu1.setStudent(name1, chinese1, math1, english1);*/
	int totalScore1 = stu1.sum(stu1);
	float averyScore1 = stu1.avery(stu1);
	bool isPassed1 = stu1.pass(stu1);
	cout << "该学生的总成绩为:" << totalScore1 << endl;
	cout << "该学生的平均成绩为:" << averyScore1 << endl;
	if (isPassed1 = true)
	{
		cout << "该学生通过了这次考试。" << endl;
	}
	else
	{
		cout << "该学生没有通过这次考试。" << endl;
	}

	printMath(stu1);

	return 0;
}

 

习题4

完成程序:药品物资管理

要求:

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

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

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

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

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

6.实现分离式编译。

 

习题5

完成程序:药品物资管理

要求:

1.创建药品类完成习题4中对药品相关的管理。

2.利用对象数组来完成对不同种类药品的信息的存储。

3.使用*this指针。

4.使用作用域为类的常量。

 

[展开全文]