我创建了一个名为Book的类,它可以有很多书。但我想创建一个类架子,只有10个以上的书籍,如果它大于10个,它应该打印错误信息!但我想不出一种制作课堂的方法。到目前为止,我已经这样做了:
#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;
}
答案 0 :(得分:2)
您可以使用标准矢量类将Book对象存储在工具架中。 在下面的示例中,将在添加到Shelf
时复制book对象#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;
}
}
};
答案 1 :(得分:1)
有很多方法可以实现这一点。请注意类Book的默认构造函数。如果您有任何疑问,请告诉我。
#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);
}