C++ 将基本语义重构为目标类
C++ Refactoring basic semantic into Objective classes
我有一个简单的程序,可以计算四种不同工人类型的工资。它是按语义编写的,但我想重构它,以便我可以让每个 worker 类型成为它自己的类。
程序的主要控件在 switch 语句中。我想做的是为每个工作线程类型创建一个类,然后通过使用适当的 setter 和 getter,执行正确的计算。
工资单.cpp
#include <iostream>
#include <iomanip>
using namespace std;
// Function Prototype
void userPrompt (void);
int main ()
{
// declare paycode and salary
int paycode;
double salary;
// run user prompt function, input paycode
userPrompt ();
cin >> paycode;
while( paycode != -1 ) {
//switch statement to handle user input
switch( paycode ) {
case 1: // manager
cout << "Manager Selected." << endl;
cout << "Enter Weekly Salary: ";
// calculate manager's salary
cin >> salary;
cout << "Manager's pay is $" << std::fixed << setprecision( 2 ) << salary << "n" << endl;
break;
case 2: // hourly worker
double wage;
int hours;
cout << "Hourly worker Selected." << endl;
cout << "Enter the hourly salary: ";
cin >> wage;
cout << "Enter the total hours worked: ";
cin >> hours;
// calculate hourly worker's pay
// with respect to possible overtime
if ( hours <= 40 )
salary = hours * wage;
else
salary = 40.0 * wage + ( hours - 40 ) * wage * 1.5;
cout << "Hourly worker's pay is $" << std::fixed << setprecision( 2 ) << salary << "n" << endl;
break;
case 3: // commission worker
int sales;
cout << "Commission Worker Selected." << endl;
cout << "Enter gross weekly sales: ";
cin >> sales;
// calculate commission worker's pay
salary = sales * 0.092 + 250;
cout << "Commission worker's pay is $" << std::fixed << setprecision( 2 ) << salary << "n" << endl;
break;
case 4: // widget worker
int widgets, wagePerWidget;
cout << "Widget Worker Selected." << endl;
cout << "Enter number of pieces: ";
cin >> widgets;
cout << "Enter wage per piece: ";
cin >> wagePerWidget;
// calculate widget worker's pay
salary = widgets * wagePerWidget;
cout << "Widget Worker's pay is $" << std::fixed << setprecision( 2 ) << salary << "n" << endl;
break;
}
// prompt user to input paycode again or exit
cout<< "Enter paycode (-1 to end): ";
cin >> paycode;
}
exit (0);
}
// userPrompt function declaration
void userPrompt (void)
{
// prompt user to input paycode
cout << "Enter paycode (-1 to end): ";
}
如果您需要学习 OOP 的基础知识,请查看一些 c++ 类设计教程。如果你能在一些研究后回答自己的问题,你会学到更多。
- http://www.tenouk.com/cplusplustutorial.html
- http://www.cpp-tips.net/Simple_class_example
- 麻省理工学院 OCW 6.088 C/C++简介
- Youtube也有一些很好的资源
相关文章:
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何重构类层次结构以避免菱形问题
- C++A*算法并不总是在路径中具有目标节点
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- 基于树莓pi的tensorflow lite量化ssd目标检测
- 为测试目标创建具有不同源文件夹的文件
- 使用源向量作为目标
- 是否可以用C++/WinRT将windows 10.0.14393作为目标
- 在 CMake 中为每个目标设置编译器/链接器标志
- qmake:检测目标位宽(32 位或 64 位)
- 如何在 CMake 中对目标依赖项进行分组?
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 如何为包含头文件的目标编写生成文件?
- 线性优化目标函数中的绝对值
- 制作文件:没有规则来制定目标:如何设置正确的规则?
- 字符串函数在目标C++上运行时C++返回空
- 如何定义自定义生成配置类型,其中通常是.exe的目标改为 DLL
- 请求最简单的 OpenMP 目标 GPU 示例
- LLVM 编译:目标的配方 '../lib/IR/Release+Asserts/Intrinsics.gen.tmp' failed
- C++ 将基本语义重构为目标类