C++简单类的实现

简单类worker的实现

一、worker.h:类的设计

#pragma once
#ifndef __WORKER__
#define __WORKER__
class worker 
{
private:
	int id;
	char *name;
	float wage;
	char level;//A,B,C代表三级或者直接就是无级
public:
	//nullptr值得总结
	worker(int Id = -1,const char*Name = nullptr, float Wage = 200, char Level = 'D')
		:id(Id), name(const_cast<char*>(Name)), wage(Wage), level(Level)
	{};
	void list();
	void set();
	void addwage();
};
#endif

二、worker.cpp:类的实现

#include"worker.h"
#include<iostream>
void worker::list() {
	std::cout << "This worker's id is " << this->id << std::endl;
	std::cout << "This worker's name is ";
	for (unsigned int i = 0; i < strlen(this->name); ++i)
		std::cout << this->name[i];
	std::cout << std::endl;
	std::cout << "This worker's wage is " << this->wage << std::endl;
	if (this->level == 'D')
		std::cout << "This worker has no level!" << std::endl;
	else
		std::cout << "This worker's level is " << this->level << std::endl;
}
void worker::set() {
	int opt = -1;
	while (opt != 0 && opt != 4) {
		std::cout << "Please input your opeation of the following opeartions:\n\t"
			<< "1:Change the id\n\t"
			<< "2:Change the name\n\t"
			<< "3:Change the wage\n\t"
			<< "4:quit\n";
		std::cin >> opt;
		switch (opt)
		{
		case 1:
			std::cout << "Please input the new id: ";
			std::cin >> this->id;
			break;
		case 2:
		{
			std::cout << "Please input the new name: ";
			char * temp = new char[6];
			std::cin.ignore(1024,'\n');
			std::cin.getline(temp, 6);
			this->name = temp;
			break;
		}
		case 3:
			std::cout << "Please input the new wage: ";
			std::cin >> this->wage;
			break;
		default:
			std::cout << "Invalid input,please input again!\n";
			continue;
		}
		std::cout << "Change successfully!\n";
		std::cout << "Do you want to continue your change?(1 for yes,0 for no): ";
		std::cin >> opt;
	}
}

void worker::addwage() {
	int di = this->level - 'D';
	switch (di)
	{
	case 0:
		this->wage += 30;
		this->level = 'C';
		break;
	case 1:
		this->wage += 50;
		this->level = 'B';
		break;
	case 2:
		this->wage += 100;
		this->level = 'A';
		break;
	default:
		std::cout << "This worker is already an A!\n" << std::endl;
		return;
	}
	std::cout << "Operated successfully!" << std::endl;
}

三、_mian.cpp:测试与调用

1、测试数据

worker A(00001,"htx",100000,'A');
worker B(00002, "hwf", 9999, 'B');
worker C(00003, "fzh", 6666);

2、测试函数.list()

void test_for_list(worker&A, worker&B,worker&C) {
	A.list();
	B.list();
	C.list();
}

![image-20201208210230421](D:_Downloads\Software\Typora\images in text\image-20201208210230421.png)

3、测试函数.set()

void test_for_set(worker&A) {
	A.set();
}

![image-20201208210354283](D:_Downloads\Software\Typora\images in text\image-20201208210354283.png)

4、测试函数.addwage()

void test_for_addwage(worker&A, worker&C) {
	A.list();
	A.addwage();
	cout << endl;
	C.list();
	C.addwage();
	C.list();
}

![image-20201208210639133](D:_Downloads\Software\Typora\images in text\image-20201208210639133.png)

posted @ 2020-12-08 23:11  关河梦断  阅读(205)  评论(0)    收藏  举报