用C++定义一个Dog类,包含的age,weight等属性,以及对这些属性的操作方法。实现并测试这个类。
时间: 2023-05-16 11:06:15 浏览: 128
实现一个C++类
好的,以下是用C++定义一个Dog类的代码:
```cpp
class Dog {
private:
int age;
double weight;
public:
Dog(int age, double weight) {
this->age = age;
this->weight = weight;
}
int getAge() {
return age;
}
double getWeight() {
return weight;
}
void setAge(int age) {
this->age = age;
}
void setWeight(double weight) {
this->weight = weight;
}
};
```
这个Dog类包含了age和weight两个属性,以及对这些属性的get和set方法。我们可以用以下代码来测试这个类:
```cpp
int main() {
Dog myDog(3, 10.5);
cout << "My dog is " << myDog.getAge() << " years old and weighs " << myDog.getWeight() << " kg." << endl;
myDog.setAge(4);
myDog.setWeight(11.2);
cout << "My dog is now " << myDog.getAge() << " years old and weighs " << myDog.getWeight() << " kg." << endl;
return 0;
}
```
输出结果为:
```
My dog is 3 years old and weighs 10.5 kg.
My dog is now 4 years old and weighs 11.2 kg.
```
这说明我们成功地定义了一个Dog类,并且能够对其属性进行操作。
阅读全文