我正在学习C++,这是我的代码:
#include <iostream>
#include <vector>
using namespace std;
enum class Genre {
unknown, fiction, nonfiction, periodical, biography, children
};
class Book {
public:
Genre getGenre() {return gen;}
void setGenre(Genre gBook) {gen=gBook;}
private:
Genre gen;
};
vector<Book> books;
void readInBooks() { // loop a few times to get some elements in books
int genre;
cout << "Please enter genre (1 fiction, 2 nonfiction, 3 periodical, 4 biography, 5 children): ";
cin >> genre;
Book b;
Genre g=Genre(genre);
b.setGenre(g);
books.push_back(b);
}
void printBooks() {
cout << "Total library:" << endl << endl;
for(int i=0;i<books.size();i++) {
cout << "Book " << i << ": " << books[i].getGenre() << endl;
}
}
int main() {
readInBooks();
printBooks();
return 0;
}
所以这行:
cout << "Book " << i << ": " << books[i].getGenre() << endl;
给出此错误:
操作符<
所以我尝试了:
friend ostream& operator<<(ostream& os, Genre& g) {
os << g.getGenre();
return os;
}
在Class Book的公开部分,出现错误:
g中属于非类类型Genre的成员getGenre的请求。
感谢您向我解释我做错了什么。
最佳答案
您的运算符与枚举有关-它与Book无关,并且不应与Book类有任何关系
因此,在定义枚举后,您可以定义用于打印它的运算符
enum class Genre {
unknown, fiction, nonfiction, periodical, biography, children
};
std::ostream& operator<< (std::ostream& os, const Genre& g)
{
switch (g) {
case Genre::unknown:
return os << "unknown";
case Genre::fiction:
return os << "fiction";
case Genre::nonfiction:
return os << "nonfiction";
case Genre::periodical:
return os << "periodical";
case Genre::biography:
return os << "biography";
case Genre::children:
return os << "children";
}
return os << static_cast<int>(g); //this line should be unreachable
// - but for future extention of enum if you forget to extend the switch as well
//I have added a protection
}