Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

c++ - Want to create object array of type Book in this program

How can I create be object array of type Book in this program. Tried to create the object but couldnt do it.Its driving me nuts. hence I need a litle help.

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

 class BOOK{
    private:
        char bookname[20];
        float bookprice;
    public:
        void getBookDetails()
        {
        cout<<"Enter the Book Name:";
         cin>>bookname;
         cout<<"Enter the Book Price:";
         cin>>bookprice;
          }
          void displayDetails()
          {
            cout<<"Book Name:"<<bookname<<endl;
            cout<<"Book Price:"<<bookprice<<endl;
          }
 };
 bool comparator(string a, string b)
 {
    return a<b;
 }
int main()
{
    int Book=5;
    string sortBook[]={"sandwich","apple","banana","zombie","pear"};
    
    std::sort(sortBook,sortBook+Book,comparator);
       for(int i=0;i<Book;i++)
    {
        cout<<sortBook[i]<<" ";
    }
}
     

}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

An object array of books would look like this:

int size = 5;
BOOK bookArray[size];

Major Problems

  • You are not using constructors
  • You are unnecessarily using char arrays
  • The string array 'sortBooks' should be a BOOK array (I assume?)
  • You declared a string array without including the string header file (probably the reason your code won't compile)

In my honest opinion, it seems that you are trying to solve a complex task without first mastering the basics of the language. I would highly recommend watching/reading a complete C++ tutorial, such as The Cherno's C++ Guide or NeuralNine's C++ Guide. Reading TutorialPoint's guides on C++ and The C++ Standard Library would also be helpful. Finally, if I had to recommend something more, I would recommend Sam's Teach Yourself C++, which helps you understand that language on a deeper level and covers many intricacies of the C++ language that beginners often overlook (note: I would not recommend using this book by itself, as it can be dry and difficult at times).

The reason your code isn't doing what you want is because you are not declaring an array of type BOOK, but of type string. Once you change the array to type book, you will run into two main problems:

  1. Declaring an array of objects requires a default constructor.
  2. Comparing classes requires operator overloading

Here is a good reference for learning about constructors. Essentially, a constructor is a special function that shares the exact same name as the class. When the class is declared, the constructor is automatically called. You should use a constructor to initialize the values instead of using the getBookDetails() function. If you used a constructor, you would just be able to write BOOK newBookObject("name", price)

Concerns

You are trying to sort an array of objects, which is difficult because objects are custom types, so the computer doesn't know how to compare two objects with a < (less than sign). Because of this, you would have to manually define how to compare the two objects (via operator overloading).

What You Need To Do:

Include the '<string>' Header File

Add #include <string> to the top of the file.

Change 'char bookname[20]' to 'string bookname'

I would not recommend using char arrays with classes, as it is difficult for a beginner. I agree with this question in that there's no reason to not using a string here, especially when you've already included the string library for the 'sortBooks' array you have at the bottom.

Add a Default Constructor

A default constructor is necessary to declare an array of objects.

BOOK()
{
    bookname = ""
    bookprice = 0.0
}

Add a Parameterized Constructor

A parameterized constuctor will allow you to declare a BOOK object like this:
BOOK newBook("book name here", price)

An Example:
BOOK newBook("Pride and Prejudice", 50.00)

BOOK(string book_name, double book_price)
{
    bookname = book_name;
    bookprice = book_price;
}

You can have two methods of the same name, as long as they have different parameters; this is called method overloading

Change the 'sortBooks' array to type BOOK

BOOK bookArray[5] { book1(title, price), book2(title, price) book3(title, price) book4(title, price) book5(title, price) }; Replace 'title' and 'price' with the appropriate titles and prices

Overload the '<' Operator

Comparing by Book Name
bool operator < (BOOK& otherBook)
{
    return bookname < otherBook.bookname;
}

Comparing by Price
bool operator < (const BOOK& otherBook)
{
    return bookprice < otherBook.bookprice;
}

Just some nitpicks/extra advice:

  • You don't have to name the data members 'bookname' and 'bookprice'. Since it's already in the context of a class, you could just write 'name' and 'price'.
  • As a beginner, you should always use doubles instead of floats, since floats have the possibility of introducing rounding errors.
  • Name classes using PascalCase

Finally, my code

I compiled this code on an Ubuntu Linux Subsystem using G++ (version: 9.3.0)

#include <iostream>
#include <string>     //Include the 'string' header 
#include <algorithm>
using namespace std;

class BOOK
{
    //Private data members
    private:
        string bookname; 
        float bookprice;

    //Public methods
    public:
        BOOK()
        {
            bookname;
            bookprice = 0.0;
        }

        BOOK(string name, double price)
        {
            bookname = name;
            bookprice = price;
        }

        void getBookDetails()
        {
            cout << "Enter the Book Name: ";
            cin >> bookname;
            //Add a 'cout << endl;' here
        

            cout << "Enter the Book Price: ";
            cin >> bookprice;
            //Add a 'cout << endl;' here
        }

        void displayDetails()
        {
            cout << "Book Name: " << bookname << endl;
            cout << "Book Price: " << bookprice << endl;
        }

        bool operator < (BOOK& otherBook)
        {
            return bookname < otherBook.bookname;  //You can access private data members within the same class
        }
};


int main()
{
    int size = 5;
    BOOK bookArray[5];   //an array of 5 'BOOK' objects

    if (bookArray[0] < bookArray[1])        //Both have the same value, "" (the default value)
        cout << "Item 1 is greater" << endl;

    return 0;
}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...