可能是最简单的面向对象入门教程(二)为什么要有类型

本文探讨了面向对象编程的核心理念,包括类型与抽象的重要性,并通过Python、C#及C++的示例代码展示了如何实现动物间的攻击行为。此外,文章还讨论了面向对象编程相较于面向过程编程的优点。

好的,继续我们上一次的问题,为什么要有类型?

我的答案是:

  节约智力成本,是智力上的一种经济方案。

当体量大到一定级别的时候,面向过程的写法管理上会非常麻烦,但是并不是说面向过程实现不了面向对象实现的功能,就是麻烦了些(可能一个月的东西要做一年)

还有一方面就是,面向对象是仿照人思考方式的,所以,很灵活,这意味着到达目的地的路面不止有一条。

那么如何看待一个问题才是面向对象的精髓,在本质一些就是如何抽象问题,类型其实是无所谓的,这些都是人为的。

OK,回到上一次的鸭子问题,其实这个问题可以看做是一个富有攻击性的动物,去攻击另一个动物,然后被攻击的受伤流血。

还是直接上代码,以下为python实现

class AttackAnimal(object):
    def attack(self,another):
        print("attack another animal")
        another.hurt()
class AnotherAnimal(object):
    hp=100
    def hurt(self):
        print('I am hurt')
        self.hp=self.hp-10
        print('hp is ',self.hp)

if __name__=='__main__':
    attAnimal=AttackAnimal()
    anoAnimal=AnotherAnimal()
    attAnimal.attack(anoAnimal)

so,狗抽象成攻击性动物(AttackAnimal),鸭子抽象成另一种能受伤的动物(AnotherAnimal)

以下用C#实现:

class AttackAnimal
    {
       public void attack(AnotherAnimal another)
        {
            Console.WriteLine("attack another");
            another.hurt();
        }
    }
    class AnotherAnimal
    {
        int hp = 100;
       public  void hurt()
        {
            Console.WriteLine("I am Hurt");
            hp -= 10;
            Console.WriteLine("hp is "+this.hp);
        }
    }
    class Program
    {

        static void Main(string[] args)
        {

            var attackAnimal = new AttackAnimal();
            var anotherAnimal = new AnotherAnimal();
            attackAnimal.attack(anotherAnimal);
         }
}    

所以说面向对象还要C# /Java这种语言啊,以下是C++实现:

 

#include "stdafx.h"
#include <iostream>
using namespace std;

class AnotherAnimal {
public:
    void hurt() {
        this->hp -= 10;
        cout << "I am hurting" << endl;
        cout << "Hp is " <<this->hp<< endl;
    }
private :
    int hp = 100;
};

class AttackAnimal{
public:
    void attack(AnotherAnimal *ano) {
        cout << "attack another animal" << endl;
        ano->hurt();
    }
};


int main()
{
    auto attacker = new AttackAnimal;
    auto another = new AnotherAnimal;
    attacker->attack(another);

    delete attacker;
    delete another;

    return 0;
}

这么看来其实C++也挺爽得,就是要手动得管理下内存,不过,问题不大。


 

那么类型如何抽象呢?

思考类型的关系,然后简化它。(这个概念在讲到接口时很深入探讨。)


 

让我们讨论一下 面向对象得好处,

第一,是易于管理代码(相比于面向过程),偏向于人得思考方式。

第二,(暂时不写)


 

那么问题来了?

为什么要抽象?必须要有抽象吗?或者说抽象会给我们什么好处让我们必须抽象?

我将在下节探讨,欢迎讨论。

 

转载于:https://www.cnblogs.com/leelds/p/9084739.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值