定义一个水果的类。要求:(1)定义3个私有的数据成员,分别为水果编号、水果名称、进价。(2)定义6个公有的成员函数,分别用于设置水果编号、水果名称、进价;显示输出水果编号、水果名称、进价。设置水果编号、水果名称、进价的函数体定义在类内,显示输出水果编号、水果名称、进价定义在类外。(3)定义水果类的对象,调用水果类中公有的成员函数
时间: 2023-02-05 07:29:38 浏览: 99
以下是定义一个水果类的代码示例:
```
class Fruit {
private:
int id; // 水果编号
string name; // 水果名称
double price; // 进价
public:
// 设置水果编号的函数
void setId(int i) {
id = i;
}
// 设置水果名称的函数
void setName(string n) {
name = n;
}
// 设置水果进价的函数
void setPrice(double p) {
price = p;
}
};
// 在类外定义显示输出水果编号的函数
void showId(Fruit f) {
cout << "水果编号:" << f.id << endl;
}
// 在类外定义显示输出水果名称的函数
void showName(Fruit f) {
cout << "水果名称:" << f.name << endl;
}
// 在类外定义显示输出水果进价的函数
void showPrice(Fruit f) {
cout << "进价:" << f.price << endl;
}
int main() {
// 定义水果类的对象
Fruit apple;
// 调用水果类中公有的成员函数
apple.setId(1);
apple.setName("苹果");
apple.setPrice(5.0);
showId(apple);
showName(apple);
showPrice(apple);
return 0;
}
```