c++对象数组写一个图书类
时间: 2023-06-04 16:06:38 浏览: 59
Sure, I can help you with that. Here's an example of how you could create a Book class with an object array in C++:
```
#include <iostream>
using namespace std;
class Book {
private:
string title;
string author;
int year;
public:
void set(string t, string a, int y) {
title = t;
author = a;
year = y;
}
void display() {
cout << title << " by " << author << " (" << year << ")" << endl;
}
};
int main() {
const int SIZE = 3; // size of the book array
Book books[SIZE]; // create the book array
// set the values for each book
books[0].set("The Great Gatsby", "F. Scott Fitzgerald", 1925);
books[1].set("To Kill a Mockingbird", "Harper Lee", 1960);
books[2].set("1984", "George Orwell", 1949);
// display the values for each book
for (int i = 0; i < SIZE; i++) {
books[i].display();
}
return 0;
}
```
In this example, the Book class has a title, author, and year attribute, along with set() and display() methods to set and display the values for each book. The main() function creates an array of three books using the Book class, sets the values for each book, and displays the values for each book using a for loop.
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)