class Book { string isbn,name,author,press; double price; public: friend ostream &operator<<(ostream &out, Book &b); friend istream &operator>>(istream &in, Book &b); }; 实现其中运算符<<、>>重载函数的定义,使其能够输入输出一个书类对象的信息。
时间: 2024-02-27 16:58:20 浏览: 64
请看下面的代码实现:
```c++
#include <iostream>
#include <string>
using namespace std;
class Book {
string isbn, name, author, press;
double price;
public:
friend ostream &operator<<(ostream &out, Book &b);
friend istream &operator>>(istream &in, Book &b);
};
ostream &operator<<(ostream &out, Book &b) {
out << "ISBN: " << b.isbn << endl;
out << "Name: " << b.name << endl;
out << "Author: " << b.author << endl;
out << "Press: " << b.press << endl;
out << "Price: " << b.price << endl;
return out;
}
istream &operator>>(istream &in, Book &b) {
cout << "ISBN: ";
in >> b.isbn;
cout << "Name: ";
in >> b.name;
cout << "Author: ";
in >> b.author;
cout << "Press: ";
in >> b.press;
cout << "Price: ";
in >> b.price;
return in;
}
int main() {
Book book;
cin >> book;
cout << book;
return 0;
}
```
在这个实现中,我们使用了 `friend` 关键字来让运算符函数访问 `Book` 类的私有成员。`operator<<` 函数用于输出一个 `Book` 类对象的信息,而 `operator>>` 函数用于输入一个 `Book` 类对象的信息。在 `main` 函数中,我们通过 `cin` 输入一个 `Book` 类对象的信息,然后通过 `cout` 输出这个对象的信息。
阅读全文