编辑代码

#include<iostream>
#include<string>
using namespace std;

//定义工人类Worker
class Worker {
private:
	int id;
	string name;
	int age;
	bool gender;
	int salary;
public:
	Worker() :id(0), name("a"), age(1),gender(0), salary(0) {}
	Worker(int Id, string Name, int Age, int g, int Salary) {
		id = Id; name = Name; age = Age; gender = g; salary = Salary;
	}
	void setWorker(int Id, string Name, int Age, int g, int Salary) {
		id = Id; name = Name; age = Age; gender = g; salary = Salary;
	}
	void operator=(const Worker& w) {  //const防止误操作
		this->id = w.id;
		this->name = w.name;
		this->age = w.age;
		this->gender = w.gender;
		this->salary = w.salary;
	}
	int getS() {
		return salary; 
	}
	int getG() {
		return gender; 
	}
	int getA() {
		return age; 
	}
	void PrintInfo() {
		if (gender)
			cout << id << " " << name << " " << age << " " << "Male" << " " << salary << endl;
		else
			cout << id << " " << name << " " << age << " " << "Female" << " " << salary << endl;
	}
};

int main()
{
	//定义对象数组存放若干个工人对象
	Worker a[4];
	int i, j, ID, Age, g, Salary;
	string Name;

	for (i = 0; i < 4; i++) {
		cout << "请输入工号: " << endl;
		cin >> ID;
		cout << "请输入姓名: " << endl;
		cin >> Name;
		cout << "请输入年龄: " << endl;
		cin >> Age;
		cout << "请输入性别: \n1、--男\n0、--女" << endl;
		cin >> g;
		cout << "请输入工资" << endl;
		cin >> Salary;
		a[i].setWorker(ID, Name, Age, g, Salary);
		cout << endl;
	}
	int lenth = sizeof(a) / sizeof(a[0]);
	//cout << "lenth=" << lenth << endl;
	cout << "按照年龄排序前: " << endl;
	for (i = 0; i < lenth; i++) {
		a[i].PrintInfo();
	}
	cout << endl;
	//实现冒泡排序,按照年龄排序
	for (i = 0; i < lenth - 1; i++) {
		for (j = 0; j < lenth - i - 1; j++) {
			if (a[j].getA() > a[j + 1].getA()) {
				Worker temp = a[j];
				a[j] = a[j + 1];
				a[j + 1] = temp;
			}
		}
	}
	cout << "按照年龄排序后: " << endl;
	for (i = 0; i < lenth; i++) {
		a[i].PrintInfo();
	}
	cout << endl;

	int SalaryFemale=0,SalaryMale=0;
	int num=0,numFemale = 0, numMale = 0;
	for (i = 0; i < lenth; i++) {
		 num+= a[i].getS();
		if (a[i].getG() == 0) {
			SalaryFemale += a[i].getS();
			numFemale++;
		}
		else {
			SalaryMale += a[i].getS();
			numMale++;
		}
	}

	cout << "全体平均工资为: " << num/lenth << endl;
	if (numMale == 0) {
		cout << "无男性工人" << endl;
	}
	else {
		cout << "男性平均工资为: " << SalaryMale / numMale << endl;
	}
	if (numFemale == 0) {
		cout << "无女性工人" << endl;
	}
	else{
		cout << "女性平均工资为: " << SalaryFemale / numFemale << endl;
	}
	system("pause");
	return 0;
}