I’m currently working on a C++ program that involves two classes: Book and library. The Book class has several private member variables, and I’m trying to access these variables from the library class. To achieve this, I’m attempting to use a friend function. Here’s the code I’m working with:
class Book{
string name;
string author;
string pages;
string edition;
string rating;
string price;
public:
void collection(void){
// Code to collect book info...
}
friend void library::search(string search);
};
class library{
public:
vector<Book> Books;
void search(string search){
for(int i=0;i<Books.size();i++){
if(Books[i].name==search){
cout<<"Book found"<<endl;
}else{
cout<<"Book not found"<<endl;
}
}
}
};
int main(){
library lab;
lab.addbook();
lab.addbook();
lab.addbook();
lab.info();
lab.search("GTHs");
return 0;
}
When I try to compile this code, I get the following errors:
./main.cpp:137:17: error: use of undeclared identifier 'library'
friend void library::search(string search);
^
./main.cpp:152:25: error: 'name' is a private member of 'Book'
if(Books[i].name==search){
^
./main.cpp:112:12: note: implicitly declared private here
string name;
I understand that the name
variable is private in the Book
class, and that’s why I’m trying to use a friend function to access it. But I’m not sure why I’m getting an error about library
being undeclared, and I’m not sure how to fix these errors.
My goal is for the program to ask for book info and then give me the required result. Can anyone help me understand what I’m doing wrong and how to fix it?
so please help me solve this error.
Bhavninder Singh Virdi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.