c++子类调用父类方法时,如何知道是哪个子类调用的
时间: 2023-08-08 09:08:30 浏览: 148
在 C++ 中,子类调用父类方法时,可以通过将子类的对象指针传递给父类方法来区分不同的子类对象。这样,父类方法就可以根据传递的子类对象指针来进行相应的处理。
例如,假设有一个父类 Animal,它有一个方法 eat(),现在有两个子类 Dog 和 Cat,它们都继承自 Animal,并且都重写了 eat() 方法。如果在某个地方需要调用 eat() 方法,可以这样做:
```c++
void function(Animal* animal) {
animal->eat();
}
Dog dog;
Cat cat;
function(&dog); // 调用 Dog 的 eat() 方法
function(&cat); // 调用 Cat 的 eat() 方法
```
在上面的示例中,通过将子类的对象指针传递给函数 function(),就可以调用相应的子类方法。在父类方法 eat() 中,可以通过 this 指针来获取当前对象的类型,从而区分不同的子类对象。例如,在 Animal 类中可以这样实现 eat() 方法:
```c++
class Animal {
public:
virtual void eat() {
if (typeid(*this) == typeid(Dog)) {
std::cout << "Dog is eating" << std::endl;
} else if (typeid(*this) == typeid(Cat)) {
std::cout << "Cat is eating" << std::endl;
} else {
std::cout << "Unknown animal is eating" << std::endl;
}
}
};
class Dog : public Animal {
public:
void eat() {
std::cout << "Dog is eating" << std::endl;
}
};
class Cat : public Animal {
public:
void eat() {
std::cout << "Cat is eating" << std::endl;
}
};
```
在上面的示例中,Animal 类中的 eat() 方法通过 typeid(*this) 获取当前对象的类型,并根据类型进行相应的处理。由于 Dog 和 Cat 类都重写了 eat() 方法,因此在调用 function() 函数时,会根据对象的实际类型来调用相应的 eat() 方法。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![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)
![](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)