第一个有用的C++程序

这是一个雇员记录系统。

这个程序包含的功能有:

(1)添加雇员的功能

(2)解雇雇员的功能

(3)雇员晋升的功能

(4)查看所有雇员的功能,包括过去以及现在的雇员

(5)添加所有当前雇员的功能

(6)添加所有以前雇员的功能

程序分为三个部分:Employee类封装了单个雇员的信息,Database类管理公司的所有雇员,一个单独的UserInterface文件提供程序的接口。

来看代码:

Employee.h:

#ifndef EMPLOYEE_H
#define EMPLOYEE_H

#include <string>
namespace Records {
    const int kDefaultStartingSalary = 30000;

    class Employee
    {
    public:
        Employee();

        void promote(int inRaiseAmount = 1000);
        void demote(int DemeritAmout = 1000);

        void hire();//hire or rehire the employee
        void fire();
        void display() const;//output employee info to console

        //Accessors and setters
        void setFirstName(std::string inFirstName);
        std::string getFirstName() const;
        void setLastName(std::string inLastName);
        std::string getLastName() const;

        void setEmployeeNumber(int inEmployeeNumber);
        int getEmployeeNumber() const;

        void setSalary(int inNewSalary);
        int getSalary() const;

        bool getIsHired() const;

    protected:
        std::string mFirstName;
        std::string mLastName;
        int mEmployeeNumber;
        int mSalary;
        bool bHired;
    };
}

#endif

Employee.cpp(雇员实现类):

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

using namespace std;

namespace Records{
    Employee::Employee():mFirstName("")
                        ,mLastName("")
                        ,mEmployeeNumber(-1)
                        ,mSalary(kDefaultStartingSalary)
    {

    }

    void Employee::promote(int inRaiseAmount)
    {
        setSalary(getSalary() + inRaiseAmount);
    }

    void Employee::demote(int inDemeritAmount)
    {
        setSalary(getSalary() - inDemeritAmount);
    }

    void Employee::hire()
    {
        bHired = true;
    }

    void Employee::fire()
    {
        bHired = false;
    }

    void Employee::display() const
    {
        cout<<"Employee: "<<getLastName()<<", "<<getFirstName()<<endl;
        cout<<"................................."<<endl;
        cout<<(bHired ? "Current Employee":"Former Employee")<<endl;
        cout<<"Employee Number: "<<getEmployeeNumber()<<endl;
        cout<<"Salary: $"<<getSalary()<<endl;
        cout<<endl;
    }

    void Employee::setFirstName(string inFirstName)
    {
        mFirstName = inFirstName;
    }

    string Employee::getFirstName() const
    {
        return mFirstName;
    }

    void Employee::setLastName(std::string inLastName)
    {
        mLastName = inLastName;
    }

    std::string Employee::getLastName() const
    {
        return mLastName;
    }

    void Employee::setSalary(int inNewSalary)
    {
        mSalary = inNewSalary;
    }

    int Employee::getSalary() const
    {
        return mSalary;
    }

    void Employee::setEmployeeNumber(int inEmployeeNumber)
    {
        mEmployeeNumber = inEmployeeNumber;
    }

    int Employee::getEmployeeNumber() const
    {
        return mEmployeeNumber;
    }

    bool Employee::getIsHired() const
    {
        return bHired;
    }

}

到这短暂测试一下,来个测试代码:

EmployeeTest.cpp:

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

using namespace std;
using namespace Records;

int main()
{
    cout<<"Testing the Employee class"<<endl;
    Employee emp;
    emp.setFirstName("Marni");
    emp.setLastName("Kleper");
    emp.setEmployeeNumber(71);
    emp.setSalary(50000);
    emp.promote();
    emp.promote(50);
    emp.hire();
    emp.display();
    return 0;
}

测试一下:(注意这里是g++)

g++ -o a Employee.cpp EmployeeTest.cpp

结果:

Testing the Employee class

Employee: Kleper, Marni

………………………

Current Employee

Employee Number: 71

Salary: $51050

测试成功。

再看Database.h:

//数据库会自动新雇员一个雇员号,因此定义了了一个常量作为编号的开始

#include <iostream>
#include <vector>
#include "Employee.h"

namespace Records{
    const int kFirstEmployeeNumber = 1000;

    class Database
    {
    public:
        Database();
        ~Database();

        Employee& addEmployee(std::string inFirstName,std::string inLastName);
        Employee& getEmployee(int inEmployeeNumber);
        Employee& getEmployee(std::string inFirstName,std::string inLastName);

        void displayAll() const;
        void displayCurrent() const;
        void displayFormer() const;

    protected:
        std::vector<Employee> mEmployees;
        int mNextEmployeeNumber;
    };
}

Database.cpp:

#include <iostream>
#include <stdexcept>
#include "Database.h"

using namespace std;

namespace Records{
    Database::Database()
    {
        mNextEmployeeNumber = kFirstEmployeeNumber;
    }

    Database::~Database()
    {
    }

    Employee& Database::addEmployee(std::string inFirstName,std::string inLastName)
    {
        Employee theEmployee;
        theEmployee.setFirstName(inFirstName);
        theEmployee.setLastName(inLastName);
        theEmployee.setEmployeeNumber(mNextEmployeeNumber++);
        theEmployee.hire();

        mEmployees.push_back(theEmployee);
        return mEmployees[mEmployees.size()-1];
    }

    Employee& Database::getEmployee(int inEmployeeNumber)
    {
    //如果不支持auto 用vector<Employee>::iterator代替auto
        //for(auto iter = mEmployee.begin();iter != mEmployee.end();++iter)
        for(vector<Employee>::iterator iter = mEmployees.begin();iter != mEmployees.end();++iter)
        {
            if(iter->getEmployeeNumber() == inEmployeeNumber)
                return *iter;
        }
        cerr<<"No Employee with number "<< inEmployeeNumber <<endl;
        throw exception();
    }

    Employee& Database::getEmployee(std::string inFirstName,std::string inLastName)
    {
        for(vector<Employee>::iterator iter = mEmployees.begin();iter != mEmployees.end();++iter)
        {
            if(iter->getFirstName() == inFirstName && iter->getLastName() == inLastName)
                return *iter;
        }
        cerr<<"No Employee with firstname named"<< inFirstName <<"and lastname named"<<inLastName<<endl;
        throw exception();
    }

    void Database::displayAll() const
    {
        //如果不支持auto 用vector<Employee>::const_iterator代替auto
        //                              (原因在于前者是const成员函数)
        for(vector<Employee>::const_iterator iter = mEmployees.begin();iter != mEmployees.end();++iter)
        {
            iter->display();
        }
    }
    void Database::displayCurrent() const
    {
        for(vector<Employee>::const_iterator iter = mEmployees.begin();iter != mEmployees.end();++iter)
        {
            if(iter->getIsHired())
                iter->display();
        }
    }
    void Database::displayFormer() const
    {
        for(vector<Employee>::const_iterator iter = mEmployees.begin();iter != mEmployees.end();++iter)
        {
            if(!iter->getIsHired())
                iter->display();
        }
    }
}

同样的道理,测试一下,

DatabaseTest.cpp:

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

using namespace std;
using namespace Records;

int main()
{
    Database myDB;
    Employee& emp1 = myDB.addEmployee("Grep","Wallis");
    emp1.fire();
    Employee& emp2 = myDB.addEmployee("Scott","Kleper");
    emp2.setSalary(100000);
    Employee& emp3 = myDB.addEmployee("Nick","Solter");
    emp3.setSalary(100000);
    emp2.promote();

    cout<<"all employees: "<<endl;
    cout<<endl;
    myDB.displayAll();
    cout<<endl;

    cout<<"current employees: "<<endl;
    cout<<endl;
    myDB.displayCurrent();
    cout<<endl;

    cout<<"former employees: "<<endl;
    cout<<endl;
    myDB.displayFormer();
    cout<<endl;

    return 0;
}

测试一下:

g++ DatabaseTest.cpp Database.cpp Employee.cpp

结果:

all employees:

Employee: Wallis, Grep

……………………………

Former Employee

Employee Number: 1000

Salary: $30000

Employee: Kleper, Scott

……………………………

Current Employee

Employee Number: 1001

Salary: $100000

Employee: Solter, Nick

……………………………

Current Employee

Employee Number: 1002

Salary: $100000

current employees:

Employee: Kleper, Scott

……………………………

Current Employee

Employee Number: 1001

Salary: $100000

Employee: Solter, Nick

……………………………

Current Employee

Employee Number: 1002

Salary: $100000

former employees:

Employee: Wallis, Grep

……………………………

Former Employee

Employee Number: 1000

Salary: $30000

测试成功。

最后的界面类,

UserInterface.cpp:

#include<iostream>
#include<stdexcept>
#include "Database.h"

using namespace std;
using namespace Records;

int displayMenu();
void doHire(Database& inDB);
void doFire(Database& inDB);
void doPromote(Database& inDB);
void doDemote(Database& inDB);

int main()
{
    Database employeeDB;
    bool done = false;
    while(!done)
    {
        int selection = displayMenu();
        switch(selection)
        {
            case 1:
                doHire(employeeDB);
                break;
            case 2:
                doFire(employeeDB);
                break;
            case 3:
                doPromote(employeeDB);
                break;
            case 4:
                employeeDB.displayAll();
                break;
            case 5:
                employeeDB.displayCurrent();
                break;
            case 6:
                employeeDB.displayFormer();
                break;
            case 0:
                done = true;
                break;
            default:
                cerr<<"Unknown command."<<endl;
        }
    }

    return 0;
}

int displayMenu()
{
    int selection;
    cout<<endl;
    cout<<"Employee Database"<<endl;
    cout<<"................."<<endl;
    cout<<"(1) Hire a new employee"<<endl;
    cout<<"(2) Fire a new employee"<<endl;
    cout<<"(3) Promote a new employee"<<endl;
    cout<<"(4) List all employees"<<endl;
    cout<<"(5) List all current employee"<<endl;
    cout<<"(6) Hire all previous employee"<<endl;
    cout<<"(0) Quit "<<endl;
    cout<<endl;
    cout<<".....>";
    cin>>selection;
    return selection;
}

void doHire(Database& inDB)
{
    string firstName;
    string lastName;
    cout<<"First Name? ";
    cin>>firstName;
    cout<<"Last Name? ";
    cin>>lastName;

    try
    {
        inDB.addEmployee(firstName,lastName);
    }
    catch(const std::exception& )
    {
        cerr<<"Unable to add new emploee!"<<endl;
    }
}

void doFire(Database& inDB)
{
    int employeeNumber;
    cout<<"Employee nuumber:";
    cin>>employeeNumber;

    try
    {
        Employee& emp = inDB.getEmployee(employeeNumber);
        emp.fire();
        cout<<"Employee "<<employeeNumber<<" terminated."<<endl;
    }
    catch(const std::exception& )
    {
        cerr<<"Unable to terminate employee!"<<endl;
    }
}

void doPromote(Database& inDB)
{
    int employeeNumber;
    int raiseAmount;
    cout<<"Employee nuumber?";
    cin>>employeeNumber;

    cout<<"How much of a raise?";
    cin>>raiseAmount;

    try
    {
        Employee& emp = inDB.getEmployee(employeeNumber);
        emp.promote(raiseAmount);
    }
    catch(const std::exception& )
    {
        cerr<<"Unable to promote employee!"<<endl;
    }
}

最终测试一下:

g++ UserInterface.cpp Database.cpp Employee.cpp

结果:

Employee Database

……………..

(1) Hire a new employee

(2) Fire a new employee

(3) Promote a new employee

(4) List all employees

(5) List all current employee

(6) Hire all previous employee

(0) Quit

…..>

这里没有将最后的测试展示出来,大家可以自己做成文件测试一下。

总的来说,整个程序逻辑较为简单,较为完全的展示了面向对象的概念。不算太难,只要有点基础,应该就能理解。不过,整个代码还是较多的,需要有点耐心。

时间: 2024-07-30 10:21:20

第一个有用的C++程序的相关文章

分享非常有用的Java程序(关键代码)(八)---Java InputStream读取网络响应Response数据的方法!(重要)

原文:分享非常有用的Java程序(关键代码)(八)---Java InputStream读取网络响应Response数据的方法!(重要) Java InputStream读取数据问题 ====================================================================== 原理讲解 1. 关于InputStream.read()      在从数据流里读取数据时,为图简单,经常用InputStream.read()方法.这个方法是从流里每次只读

20个非常有用的Java程序片段--转

原文地址:http://geek.csdn.net/news/detail/236591 下面是20个非常有用的Java程序片段,希望能对你有用. 1. 字符串有整型的相互转换 String a = String.valueOf(2); //integer to numeric string int i = Integer.parseInt(a); //numeric string to an int 2. 向文件末尾添加内容 BufferedWriter out = null; try { o

分享非常有用的Java程序(关键代码)(七)---抓屏程序

原文:分享非常有用的Java程序(关键代码)(七)---抓屏程序 import java.awt.Dimension; import java.awt.Rectangle; import java.awt.Robot; import java.awt.Toolkit; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import java.io.File; ... public void captureScre

分享非常有用的Java程序 (关键代码)(五)---把 Array 转换成 Map

原文:分享非常有用的Java程序 (关键代码)(五)---把 Array 转换成 Map import java.util.Map; import org.apache.commons.lang.ArrayUtils; public class Main { public static void main(String[] args) { String[][] countries = { { "United States", "New York" }, { &quo

分享非常有用的Java程序 (关键代码)(六)---解析/读取XML 文件(重要)

原文:分享非常有用的Java程序 (关键代码)(六)---解析/读取XML 文件(重要) XML文件 <?xml version="1.0"?> <students> <student> <name>John</name> <grade>B</grade> <age>12</age> </student> <student> <name>Mar

分享非常有用的Java程序 (关键代码) (三)---创建ZIP和JAR文件

原文:分享非常有用的Java程序 (关键代码) (三)---创建ZIP和JAR文件 import java.util.zip.*; import java.io.*; public class ZipIt { public static void main(String args[]) throws IOException { if (args.length < 2) { System.err.println("usage: java ZipIt Zip.zip file1 file2 f

分享非常有用的Java程序 (关键代码)(四)---动态改变数组的大小

原文:分享非常有用的Java程序 (关键代码)(四)---动态改变数组的大小 /** * Reallocates an array with a new size, and copies the contents * * of the old array to the new array. * * @param oldArray the old array, to be reallocated. * * @param newSize the new array size. * * @return

分享非常有用的Java程序 (关键代码) (一)

原文:分享非常有用的Java程序 (关键代码) (一)   分享一些非常有用的Java程序 (关键代码) ,希望对你有所帮助. 1.  得到当前方法的名字 String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); 2. 转字符串到日期 java.util.Date = java.text.DateFormat.getDateInstance().parse(date String); 或者是: S

分享非常有用的Java程序 (关键代码) (二)---列出文件和目录

原文:分享非常有用的Java程序 (关键代码) (二)---列出文件和目录 File dir = new File("directoryName"); String[] children = dir.list(); if (children == null) { // Either dir does not exist or is not a directory } else { for (int i=0; i < children.length; i++) { // Get f