类的多态

类的多态

  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++中,可以通过`public`, `protected`, 和`private`关键字指定继承方式[^3]。例如: ```cpp class Base { protected: int value; public: Base(int v) : value(v) {} void showValue() const { std::cout << "Base Value: " << value << std::endl; } }; class Derived : public Base { public: Derived(int v) : Base(v) {} void modifyValue(int new_val) { value = new_val; } }; ``` 在此示例中,`Derived` 从 `Base` 继承而来,并能够访问其受保护成员 `value`。 --- #### 二、多态的基础 多态是指同一接口可以表示多种型的对象的能力。C++ 支持两种形式的多态:编译时多态(静态多态性)和运行时多态(动态多态性)。 ##### (1)编译时多态 编译时多态通常通过函数重载和运算符重载实现。例如: ```cpp void Swap(int& a, int& b) { int temp = a; a = b; b = temp; } void Swap(double& a, double& b) { double temp = a; a = b; b = temp; } ``` 这里展示了两个不同型的 `Swap` 函数,在编译阶段根据传入参数型选择合适的版本[^4]。 --- ##### (2)运行时多态 运行时多态则依赖于虚函数机制。为了支持动态绑定,需将基中的某些函数声明为虚拟函数(virtual function)。这样即使通过基指针或引用调用这些函数,也会依据实际对象型执行相应的派生版本。 以下是具体实例说明如何利用虚函数达成运行时多态效果[^5]: ```cpp #include <iostream> using namespace std; // 基定义 class Shape { public: virtual float getArea() const = 0; // 纯虚函数使Shape成为抽象 virtual ~Shape() {} // 虚析构函数确保正确释放资源 }; // 圆形派生自形状 class Circle : public Shape { private: float radius; public: Circle(float r) : radius(r) {} float getArea() const override { return 3.14f * radius * radius; } void displayInfo() const { cout << "This is a circle." << endl; } }; // 正方形也派生于形状 class Square : public Shape { private: float sideLength; public: Square(float s) : sideLength(s) {} float getArea() const override { return sideLength * sideLength; } void displayDetails() const { cout << "Square with sides of length " << sideLength << "." << endl; } }; int main() { Shape* shapes[] = {new Circle(7), new Square(5)}; // 动态分配内存给数组元素 for(auto shape : shapes){ cout << "The area is: " << shape->getArea() << endl; // 多态调用 delete shape; // 清理堆上的对象 } return 0; } ``` 此例子中,尽管存储的是 `Shape*` 型指针,但由于存在虚函数表的支持,每次都能准确找到对应的具体实现逻辑并加以应用。 --- ### 总结 综上所述,理解并熟练掌握继承以及多态对于深入学习C++至关重要。它们共同构成了强大的工具集,帮助开发者构建灵活且易于维护的应用软件架构。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值