Как связать пользователя с книгой (библиотечная система) C ++ - PullRequest
0 голосов
/ 04 мая 2020

Я занимаюсь университетским проектом и создаю библиотечную систему. У него есть несколько ограничений, я не могу использовать то, чему нас не учили (поэтому нет векторов или std :: вещи) Теперь у меня есть несколько классов.

(1) Дата (2) Книга (3) Студент (4) Библиотека // Еще не сделали

Теперь, когда студент / пользователь выдает книгу, его номер аккаунта сохраняется в классе "Книга", как и return_date. Теперь я sh создаю указатель или использую оператор this -> или что-то еще, что будет в классе Student, но указывает на класс Book. Таким образом, когда ученик захочет увидеть, какие книги он выпустил, он будет показан. Я не уверен, как это сделать. Должен ли я создать класс библиотеки, присвоить ему массив классов «Книга» по составу, а затем создать функцию-член в классе «Студент / пользователь» и отобразить ее там?

Я действительно хочу использовать new / delete ключевое слово, это или указатели, чтобы сделать это. Это не обязательно, но это поможет мне понять эти понятия.

Ниже приведены мои классы Книги, Студента и Даты.

Дата Класс:

class Date
{
    int Day;        //1-31 based on month
    int Month;      //1-12
    int Year;       //any year
    int checkDay(int );
    int Late_Days;

public:
    static const int Days_per_Month[13];
    Date()
    {
        Day=0;
        Month=0;
        Year=0;
    }
    Date (int dy, int mn, int yr)
    {
        if (mn>0 && mn <=12)
            Month=mn;
        else
        {
            Month=1;
            cout<<"Month "<<mn<<" invalid. Set to month 1"<<endl;
        }
        Year=yr;
        Day=checkDay(dy);
    }

    void setDay(int d)          {Day=d;}
    void setMonth(int m)        {Month=m;}
    void setYear(int y)         {Year=y;}
    void setLateDay(int LD)     {Late_Days=LD;}
    int getDay()                {return Day;}
    int getMonth()              {return Month;}
    int getYear()               {return Year;}
    int getLateDay()            {return Late_Days;}


    void Print_Date()
    {
        cout<<getDay()<<"/"<<getMonth()<<"/"<<getYear()<<endl;
        //cout<<Day<<"/"<<Month<<"/"<<Year<<endl;
    }

    void Update_Date()
    {
        cout<<"\nEnter Day: ";
        cin>>Day;
        cout<<"Enter Month: ";
        cin>>Month;
        cout<<"Year: ";
        cin>>Year;
    }
    void increment_date(int num)
    {
        int day;
        int month_new;
       // Day=Day+num;

        setDay(getDay()+num);


        if(    getDay()>Days_per_Month[getMonth()]     )
        {
            day=getDay()-Days_per_Month[getMonth()];
            setDay(day);
            setMonth(getMonth()+1);
            if(Days_per_Month[getMonth()]>12)
            {
                month_new=1;
                setMonth(month_new);
                setYear(getYear()+1);
            }
        }
        Print_Date();
    }
const int Date:: Days_per_Month[13]={0,31,28,31,30,31,30,31, 31, 30, 31, 30, 31};
int Date::checkDay(int testday)     //returntype classname :: funcname (parameteres)
{
    //static const int Days_per_Month[13]={0,31,28,31,30,31,30,31, 31, 30, 31, 30, 31};
    if(testday > 0 && testday <= Days_per_Month[Month])
        return testday;
    if ( Month==2 && testday==29 && (Year%400==0 || (Year%4==0 && Year%100!=0)) )  //for leap year
        return testday;

    cout<<"Day "<<testday<<" invalid. Set to day 1."<<endl;
    return 1;
}

Книжный класс

class Book
{
    string Title;
    string Author;
    unsigned long int ISBN;
    int Year_of_Publication;
    int Library_Code;
    string Category;
    string Status;
    unsigned int Account_Number; //if issued
    int Copies_of_Book;
    Date Return_Date;

public:
    static int Copy_Number;
    Book()
    {
        Title=" ";
        Author=" ";
        ISBN=0;
        Year_of_Publication=0;
        Library_Code=0;
        Category=" ";
        Status=" ";
        Account_Number=0;
        Copies_of_Book=0;
        Return_Date.setDay(0);
        Return_Date.setMonth(0);
        Return_Date.setYear(0);
    }
    Book(string t, string a,unsigned long int isbn, int yop, int libcode, string c, string s, unsigned int an, int cob)
    {
        setTitle(t);
        setAuthor(a);
        setISBN(isbn);
        setYOP(yop);
        setLibraryCode(libcode);
        setCategory(c);
        setStatus(s);
        setAccountNum(an);
        setCopiesBook(cob);
    }

    void setTitle(string T)             {Title=T;}
    void setAuthor(string A)            {Author=A;}
    void setISBN(unsigned long int isbn){ISBN=isbn;}
    void setYOP(int yop)                {Year_of_Publication=yop;}
    void setLibraryCode(int libcode)    {Library_Code=libcode;}
    void setCategory(string c)          {Category=c;}
    void setStatus(string s)            {Status=s;}
    void setAccountNum(unsigned int an) {Account_Number=an;}
    void setCopiesBook(int cob)         {Copies_of_Book=cob;}
    void setCopyNumber(int cn)          {Copy_Number=cn;}

    string getTitle()                   {return Title;}
    string getAuthor()                  {return Author;}
    unsigned long int getISBN()         {return ISBN;}
    int getYOP()                        {return Year_of_Publication;}
    int getLibraryCode()                {return Library_Code;}
    string getCategory()                {return Category;}
    string getStatus()                  {return Status;}
    unsigned int getAccountNum()        {return Account_Number;}
    int getCopiesBook()                 {return Copies_of_Book;}
    int getCopyNumber()                 {return Copy_Number;}

    void Input_New_Book()
    {
        cout<<"\nEnter Title: ";
        cin>>Title;
        cout<<"Enter Author: ";
        cin>>Author;
        cout<<"Enter ISBN: ";
        cin>>ISBN;
        cout<<"Enter Year of Publication: ";
        cin>>Year_of_Publication;
        cout<<"Enter Library Code: ";
        cin>>Library_Code;
        cout<<"Enter Category: ";
        cin>>Category;
        cout<<"Enter Total Copies Number: ";
        cin>>Copies_of_Book;
        cout<<"Enter Status: ";
        cin>>Status;
        if(Status=="Issued")
        {
        cout<<"Enter Account Number: ";
        cin>>Account_Number;
        Return_Date.Update_Date();
        }
    }

    void Display_Book_Info()
    {
        cout<<"\nTitle: "<<getTitle()<<endl;
        cout<<"Author: "<<getAuthor()<<endl;
        cout<<"ISBN: "<<getISBN()<<endl;
        cout<<"Year of Publication: "<<getYOP()<<endl;
        cout<<"Library Code: "<<getLibraryCode()<<endl;
        cout<<"Category: "<<getCategory()<<endl;
        cout<<"Total Copies: "<<getCopiesBook()<<endl;
        cout<<"Status: "<<getStatus()<<endl;
        if(getStatus()=="Issued")
        {
        cout<<"Account Number: "<<getAccountNum()<<endl;
        cout<<"Return Date: ";
        Return_Date.Print_Date();
        }
    }

    void Update_Status()
    {
        unsigned int AN;
        Display_Book_Info();
        cout<<"Please enter the updated status of the book: ";
        cin>>Status;                //We cannot use string in an switch, so we are using if.
            if (Status=="Lost")
            {
                cout<<"The book is lost."<<endl;
                setAccountNum(0);
            }
            else if (Status=="Available")
            {
                cout<<"Book is available now to issue."<<endl;
                setAccountNum(0);       //This indicates it doesn't have nay account number.
            }
            else if(Status=="Issued")
            {
                cout<<"The book is in possession of someone."<<endl;
                cout<<"Enter their account number:";
                cin>>AN;
                setAccountNum(AN);
            }
            else if (Status=="Order")
            {
                cout<<"The book is in process of being ordered."<<endl;
                setAccountNum(0);
            }
            else
            {
                cout<<"Wrong entry!\nBook's Status is set to default. (Available)"<<endl;
                Status="Available";
                setAccountNum(0);
            }
    cout<<"Status updated successfully!"<<endl;
    }
    void Issue_Book(int day_num)      //This day_num indicated number of days.
    {
        unsigned int an;
        cout<<"Enter account number of User:";
        cin>>an;
        setAccountNum(an);
        Return_Date.Update_Date();
        cout<<"Book issued for "<<day_num<<" days."<<endl;
        cout<<"Return Date: ";
        Return_Date.Print_Date();
    }

    void ReIssue_Book(int day_num)
    {
        unsigned int an;
        cout<<"Enter account number of User:";
        cin>>an;
        setAccountNum(an);
        Return_Date.increment_date(day_num);
        cout<<"Book issued for "<<day_num<<" more days."<<endl;
        cout<<"Return Date: ";
        Return_Date.Print_Date();
    }


    void Return_Book()
    {
        cout<<"Book returned from User: "<<getAccountNum()<<endl;
        setAccountNum(0);
        cout<<"Book returned successfully!"<<endl;
    }

}; //end of class book
int Book::Copy_Number=0;

Студенческий класс

class Student:public Book
{
    string Name;
    unsigned int Account_Number;
    double Fine;
    int Books_Issue;

public:
    Student()
    {
        Name=" ";
        Account_Number=0;
        Fine=0;
        Books_Issue=0;
    }

    void setName(string n)                      {Name=n;}
    void setAccount_Number(unsigned int an)     {Account_Number=an;}
    void setFine(double f)                      {Fine=f;}
    void setBooksIssue(int n)                   {Books_Issue=n;}

    string getName()                            {return Name;}
    unsigned int getAccount_Number()            {return Account_Number;}
    double getFine()                            {return Fine;}
    int getBooksIssue()                         {return Books_Issue;}

    void Input_Student_info()
    {
        cout<<"\nEnter Name: ";
        cin>>Name;
        cout<<"Enter Account Number: ";
        cin>>Account_Number;
    }
    void Display_Student_info()
    {
        cout<<"Name: "<<getName()<<endl;
        cout<<"Account Number: "<<getAccount_Number()<<endl;
        cout<<"Total Fine: "<<getFine()<<endl;
        cout<<"Books issued: "<<getBooksIssue()<<endl;
    }
    void Issue_a_book()
    {
        if(Books_Issue<=3)
        {
            Issue_Book(7);  //This will issue a book and give it a 7 days return date time
            Books_Issue++; //This will mean a book has been issued.
        }
        else
            cout<<"Cannot issue book. You have reached your maximum limit.\nReturn a book in order to issue another."<<endl;
    }
    void Display_All_Books()        //which are currently issued
    {
        for (int i=0 ; i<=getBooksIssue() ; i++)
        {

        }
    }
};

Извините за публикацию огромных кусков кода. Но некоторые люди говорят, что мы должны публиковать весь код, поэтому я и разместил все это организованным способом.

Основной вопрос:

Как мне отобразить издал книги в студенческом классе? Должен ли я создать класс Библиотеки (как родительский класс или дочерний класс, или использовать композицию и массивы класса Book) первым или в самом конце? Дайте мне знать, как лучше всего это сделать.

Большое спасибо.

1 Ответ

0 голосов
/ 04 мая 2020
  1. Лучше удалить детали проблемы пользователя из класса книги ... Пусть в классе книги есть только сведения о книге и методах для обновления и получения сведений о книге.

  2. Добавление сведений о проблеме пользователя в новый класс, который наследует класс книги ... Этот способ является более модульным и сохраняет книги как отдельные объекты. Теперь вы можете создать связанный список (поскольку они являются динамическими c) или массив этих классов, каждый из которых содержит книгу, а также даты выпуска и возврата для этого конкретного студента.

для пример:

class books_issued{
public: book issued_book;
        books_issued *new;

        <put your issue data like:>
        unsigned int Account_Number; //if issued
        int Copies_of_Book;
        Date Return_Date;

       <and issue related methods:>

};

теперь объявляем объект класса books_issued в классе ученика и пишем метод для добавления, удаления и просмотра книг, которые были выпущены этим конкретным учеником.

--- Если вам нужна помощь в создании связанных списков для этой цели, дайте мне знать, что я буду очень рад помочь, так как я сделал очень похожую программу управления библиотеками для своего проекта: - ) ---

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...