设计一个表示猫的类,包括猫的颜色、体重、年龄等数据,具有设置猫的颜 色,修改和显示猫的体重、年龄等操作用c++实现
时间: 2024-02-01 17:13:28 浏览: 127
以下是用 C++ 实现的猫的类:
```cpp
class Cat {
private:
string color;
double weight;
int age;
public:
void setColor(string c) {
color = c;
}
void setWeight(double w) {
weight = w;
}
void setAge(int a) {
age = a;
}
void modifyWeight(double w) {
weight += w;
}
void modifyAge(int a) {
age += a;
}
void display() {
cout << "Color: " << color << endl;
cout << "Weight: " << weight << " kg" << endl;
cout << "Age: " << age << " years old" << endl;
}
};
```
使用示例:
```cpp
int main() {
Cat myCat;
myCat.setColor("White");
myCat.setWeight(4.5);
myCat.setAge(3);
myCat.display();
// Output: Color: White
// Weight: 4.5 kg
// Age: 3 years old
myCat.modifyWeight(-0.5);
myCat.modifyAge(1);
myCat.display();
// Output: Color: White
// Weight: 4 kg
// Age: 4 years old
return 0;
}
```
阅读全文