Reputation: 37
I have created a class called Book and it can have many Books. But I want to create a class shelf which can contain only 10 of Books if it is greater than than 10 ten it should print Error Message! But I cannot think of a way to make class shelf. So far I have done this :
#include <iostream>
#include <string>
using namespace std;
class Book{
private:
string bookName;
int pNum;
public:
Book();
Book(string tempName, int tNum){
setName(tempName);
setPageNum(tNum);
}
void setName(string bName){
bookName = bName;
}
void setPageNum(int tempNum){
pNum = tempNum;
}
string getName(){
return bookName;
}
int getPageNum(){
return pNum;
}
};
class Shelf{
public:
Book nBook[10];
void addbook();
void Book::addbook(Book nBook[10])
{
for(int i = 0; i<10; i++)
nBook[i] = nBook[i].setName(string bName)
}
};
int main(){
Book math = Book("math", 500);
Book abcd = Book("abcd", 501);
cout << English.getName() <<" "<<English.getPageNum()<<endl;
cout << German.getName() <<" "<<German.getPageNum()<<endl;
}
Upvotes: 0
Views: 80
Reputation: 347
You can use the standard vector class to store the Book objects in the shelf. In the example below, the book object will be copied when added to the Shelf
#include <vector>
using namespace std;
class Shelf{
public:
vector<Book> books;
bool addbook(Book book)
{
if(books.size() > 10)
{
return false;
}
else
{
books.push_back(book);
return true;
}
}
};
Upvotes: 2
Reputation: 532
There are many ways to implement this. Note the default constructor of class Book. Let me know if you have any questions.
#include <iostream>
#include <string>
using namespace std;
class Book{
private:
string bookName;
int pNum;
public:
Book(){
}
Book(string tempName, int tNum){
setName(tempName);
setPageNum(tNum);
}
void setName(string bName){
bookName = bName;
}
void setPageNum(int tempNum){
pNum = tempNum;
}
string getName(){
return bookName;
}
int getPageNum(){
return pNum;
}
};
class Shelf{
public:
Book nBook[10];
int numberOfBooks;
void addbook(Book);
Shelf()
{
numberOfBooks = 0;
}
bool addBook(Book newBook)
{
if (numberOfBooks == 10)
{
return false;
}
else
{
nBook[numberOfBooks] = newBook;
numberOfBooks++;
return true;
}
}
};
int main(){
Book English = Book("math", 500);
Book German = Book("abcd", 501);
Shelf bookShelf = Shelf();
bookShelf.addBook(English);
}
Upvotes: 1