C++源代码构建一个类Book,其中含有两个私有数据成员number(数量)和price(价格),编写测试main函数, 建立一个有5个元素的数组对象,将number初始化为1~5,将price 初始化为number的10倍,显示每个对象的number*price值。
时间: 2024-06-03 15:08:17 浏览: 64
#include <iostream>
using namespace std;
class Book {
private:
int number;
int price;
public:
Book(int num, int pri) {
number = num;
price = pri;
}
int getNumber() {
return number;
}
int getPrice() {
return price;
}
int getTotal() {
return number * price;
}
};
int main() {
Book bookArray[5] = { Book(1, 10), Book(2, 20), Book(3, 30), Book(4, 40), Book(5, 50) };
for (int i = 0; i < 5; i++) {
cout << "Book " << i+1 << " total price: " << bookArray[i].getTotal() << endl;
}
return 0;
}
阅读全文