Define a Pet class that stores the pet’s name, age, and weight. Add appropriate constructors, accessor, and mutator functions. Also define a function named getLifespan that returns a string with the value “unknown lifespan.” Next, define a Dog class that is derived from Pet. The Dog class should have a private member variable named breed that stores the breed of the dog. Add mutator and accessor functions for the breed variable and appropriate constructors. Redefine the getLifespan function to return "Approximately 7 years" if the dog’s weight is over 100 pounds and "Approximately 13 years" if the dog’s weight is under 100 pounds. Next, define a Rock class that is derived from Pet. Redefine the getLifespan function to return “Thousands of years”. Finally, write a test program that creates instances of pet rocks and pet dogs that exercise the inherited and redefined functions in C++.
时间: 2024-03-18 19:41:17 浏览: 71
以下为C++代码实现:
```cpp
#include <iostream>
#include <string>
using namespace std;
// 宠物类
class Pet {
protected:
string name;
int age;
double weight;
public:
Pet(string name, int age, double weight) {
this->name = name;
this->age = age;
this->weight = weight;
}
string getName() {
return name;
}
int getAge() {
return age;
}
double getWeight() {
return weight;
}
void setName(string name) {
this->name = name;
}
void setAge(int age) {
this->age = age;
}
void setWeight(double weight) {
this->weight = weight;
}
virtual string getLifespan() {
return "unknown lifespan";
}
};
// 狗类
class Dog : public Pet {
private:
string breed;
public:
Dog(string name, int age, double weight, string breed)
: Pet(name, age, weight) {
this->breed = breed;
}
string getBreed() {
return breed;
}
void setBreed(string breed) {
this->breed = breed;
}
virtual string getLifespan() {
if (weight > 100) {
return "Approximately 7 years";
} else {
return "Approximately 13 years";
}
}
};
// 岩石类
class Rock : public Pet {
public:
Rock(string name, int age, double weight)
: Pet(name, age, weight) {}
virtual string getLifespan() {
return "Thousands of years";
}
};
// 测试代码
int main() {
Pet* pet1 = new Rock("Rocky", 1000, 1000);
Pet* pet2 = new Dog("Fido", 3, 80, "Golden Retriever");
cout << pet1->getName() << ", " << pet1->getLifespan() << endl;
cout << pet2->getName() << ", " << pet2->getLifespan() << endl;
delete pet1;
delete pet2;
return 0;
}
```
运行结果为:
```
Rocky, Thousands of years
Fido, Approximately 13 years
```
阅读全文