子类的构造函数传入父类指针的好处及具体示例
时间: 2023-09-29 20:09:44 浏览: 98
传入父类指针的好处是可以让子类对象拥有父类的所有成员和方法,同时还可以在子类对象中添加自己的成员和方法。这样可以实现代码的复用和扩展性的提升。
具体示例如下:
```c++
class Animal {
public:
virtual void eat() {
std::cout << "Animal eats." << std::endl;
}
};
class Dog : public Animal {
public:
void eat() override {
std::cout << "Dog eats." << std::endl;
}
};
class Cat : public Animal {
public:
void eat() override {
std::cout << "Cat eats." << std::endl;
}
};
class AnimalShelter {
public:
AnimalShelter(Animal* animal) : m_animal(animal) {}
void feed() {
m_animal->eat();
}
private:
Animal* m_animal;
};
int main() {
Animal* dog = new Dog();
AnimalShelter dogShelter(dog);
dogShelter.feed(); // 输出 "Dog eats."
Animal* cat = new Cat();
AnimalShelter catShelter(cat);
catShelter.feed(); // 输出 "Cat eats."
return 0;
}
```
在上述示例中,我们定义了一个`Animal`类作为父类,然后派生出了`Dog`和`Cat`两个子类,分别重写了`eat()`方法。`AnimalShelter`类是一个动物收容所的类,它的构造函数接受一个`Animal`类型的指针,然后在`feed()`方法中调用这个指针所指向的对象的`eat()`方法。
在`main()`函数中,我们分别创建了一个`Dog`对象和一个`Cat`对象,并将它们分别传入到`AnimalShelter`类中进行喂食。由于`Dog`和`Cat`类都继承自`Animal`类并重写了`eat()`方法,所以它们在`feed()`方法中表现出了不同的行为。这个示例就是一个典型的通过传入父类指针来实现子类扩展的例子。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![text/x-c++](https://img-home.csdnimg.cn/images/20250102104920.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)