函数重载可用于实现多态性,即通过基类指针调用派生类方法,编译器根据实际参数类型选择重载版本。示例中,animal 类定义虚拟 makesound() 函数,dog 和 cat 类重写该函数,通过 animal* 指针调用 makesound() 时,编译器会基于指向的对象类型调用相应的重写版本,从而实现多态性。

C++ 函数重载如何实现多态性
什么是函数重载?
函数重载是一种将多个具有相同名称但参数类型或数量不同的函数定义于同一作用域内的编程技术。
立即学习“C++免费学习笔记(深入)”;
如何使用函数重载实现多态性?
多态性是一种允许通过基类指针或引用调用派生类方法的功能。C++ 中函数重载与多态性的关系如下:
实战示例
以下代码展示了如何使用函数重载实现多态性:
#include <iostream>
class Animal {
public:
virtual void makeSound() { // 声明为虚函数
std::cout << "Animal sound" << std::endl;
}
};
class Dog : public Animal {
public:
void makeSound() override { // 重写 makeSound()
std::cout << "Woof woof" << std::endl;
}
};
class Cat : public Animal {
public:
void makeSound() override { // 重写 makeSound()
std::cout << "Meow meow" << std::endl;
}
};
int main() {
Animal* animalptr; // 基类指针
// 指向 Dog 对象
animalptr = new Dog();
animalptr->makeSound(); // 调用 Dog::makeSound()
// 指向 Cat 对象
animalptr = new Cat();
animalptr->makeSound(); // 调用 Cat::makeSound()
delete animalptr;
return 0;
}输出:
Woof woof Meow meow
以上就是C++ 函数重载如何实现多态性?的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号