类的多态

类的多态

  1. 不同的类实例化,实例再调用自己的方法
class Animal(object):
    # def __init__(self, name):
    #     self.name = name

    def run(self):
        print('动物在跑')

class Cat(Animal):
    def run(self):
        print('猫在跑')

class Dog(Animal):
    def run(self):
        print('狗在跑')

class Pig(Animal):
    pass
class Bird(Animal):
    pass
class Monkey(Animal):
    pass

cat1 = Cat()
dog1 = Dog()
cat1.run()
dog1.run()
  1. 把上面的语句封装成函数
def animal_run(class_instance):     # 参数接收的是一个类实例
    class_instance.run()        # 传入cat执行cat.run() ,传入dog执行dog.run()
    class Animal(object):
    # def __init__(self, name):
    #     self.name = name

    def run(self):
        print('动物在跑')

class Cat(Animal):
    def run(self):
        print('猫在跑')

class Dog(Animal):
    def run(self):
        print('狗在跑')

class Pig(Animal):
    pass
class Bird(Animal):
    pass
class Monkey(Animal):
    pass

cat1 = Cat()
dog1 = Dog()
animal_run(cat1)
animal_run(dog1)

多态:一段已写好业务逻辑代码,传入的实例不同,最终运行出的代码也跟着变化。一种程序可以有多种运行时状态,所以叫多态。
多态是类的三大特性之一。
好处:代码灵活。

C++中的多态性是面向对象编程的一个重要概念,它允许使用基的指针或引用来调用派生的方法。C++中的多态性可以通过两种方式实现:多态和函数多态。 1. 多态多态是通过继承和虚函数来实现的。当基的指针或引用指向派生的对象时,可以通过虚函数来调用派生中的方法。这种调用方式是动态绑定的,即在运行时确定调用的是哪个方法。这种动态绑定是通过虚函数表和虚函数表指针来实现的[^1]。 范例: ```cpp #include <iostream> class Shape { public: virtual void draw() { std::cout << "Drawing a shape." << std::endl; } }; class Circle : public Shape { public: void draw() override { std::cout << "Drawing a circle." << std::endl; } }; class Rectangle : public Shape { public: void draw() override { std::cout << "Drawing a rectangle." << std::endl; } }; int main() { Shape* shape1 = new Circle(); Shape* shape2 = new Rectangle(); shape1->draw(); // 输出:Drawing a circle. shape2->draw(); // 输出:Drawing a rectangle. delete shape1; delete shape2; return 0; } ``` 2. 函数多态: 函数多态是通过函数重载和模板来实现的。函数重载允许在同一个作用域中定义多个同名函数,但它们的参数型或个数不同。当调用这些同名函数时,编译器会根据实参的型或个数来选择合适的函数进行调用。这种调用方式是静态绑定的,即在编译时确定调用的是哪个函数。模板是一种通用的函数或,它可以根据实参的型自动生成对应的函数或。 范例: ```cpp #include <iostream> void print(int num) { std::cout << "Printing an integer: " << num << std::endl; } void print(double num) { std::cout << "Printing a double: " << num << std::endl; } template <typename T> void print(T value) { std::cout << "Printing a value: " << value << std::endl; } int main() { print(10); // 输出:Printing an integer: 10 print(3.14); // 输出:Printing a double: 3.14 print("Hello"); // 输出:Printing a value: Hello return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值