I am writing a program for class that is asking us to create a class of "book". We are then supposed to create new instantiations of that class upon demand from the user. I am new to C++ so I am attempting to code this out but am running into a problem.
The main problem is how do I instantiate a class with a variable if I don't know how many I will have to do ahead of time. The user could ask to add 1 book or 1000. I am looking at this basic code:
This is the simple code I started with. I wanted to have an index int keep a number and have the book class I create be called by that int (0, 1, 2, etc...) So I attempted to convert the incoming index in开发者_StackOverflowt into a string, but I'm kind of stuck from here.
void addBook(int index){
string bookName;
std::stringstream ss;
ss << index;
book bookName;
cout << "Enter the Books Title: ";
cin >> bookName.title;
}
But obviously this doesn't work as "bookName" is a string to the computer and not the class member I tried to create.
All of the tutorials I have seen online and in my text show the classes being instantiated with names in the code, but I just don't know how to make it variable so I can create any amount of "books" that the user might want. Any insight on this would be appreciated. Thank you for your time.
Given your type book
, if you want to create a list of books, try using a container like std::vector
, std::list
or std::deque
.
typedef std::vector<book> library_type;
library_type library;
book catch22("Catch 22")
library.push_back(catch22);
book haltingState("Halting State");
library.push_back(haltingState);
You can create books and add to the library from a loop, which sounds like what you want.
Your choice of container type will depend on the access pattern you want. For example, a std::vector
is good if you want to add books like this and you rarely want to remove them in an arbitrary order. It's fairly straightforward to change the type later if you change your mind about this.
As Matt mentioned above, what you want to do is create a class called book first. In your constructor, you can set various parameters like title, author, ID, or whatever you need. Something like (note that the compiler knows to assign the parameters to the class member variables even if they have the same name):
Book(int ID, std::string name) : ID(ID), name(name)
{}
with your class looking something like this:
class Book
{
private:
int ID;
std::string name;
public:
//constructor, etc.
};
Also, again as mentioned, vectors are probably a good first choice unless you need some specific functionality. For your input, try a do...while loop if the user will input at least one book.
精彩评论