c语言中struct和c++中class实例对比

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sty945/article/details/82942489

前言

实现游戏中简单的打怪升级的功能

c语言中的struct

#include <stdio.h>

typedef void(*Train)(struct player*, int);
typedef void(*Pk)(struct player*, struct player*);

struct player
{
    int level;   //等级
    int hp;      //hp值
    Train f_train;  //函数指针(练级)
    Pk f_pk;        //函数指针(PK)
};

void train_fun(struct player *p1, int nums)
{
    int killnums = p1->hp > nums ? nums: p1->hp;
    p1->level += killnums;
    p1->hp -= killnums;
    printf("练级:长了%d级", killnums);
    printf("当前:level=%d, hp=%d\n", p1->level, p1->hp);
}


void pk_fun(struct player *p1, struct player *p2)
{
    int power1 = p1->level * 100 + p1->hp;
    int power2 = p2->level * 100 + p2->hp;
    if (power1 >= power2)
    {
        printf("player1 win\n");
    }
    else
    {
        printf("player2 win\n");
    }

}


int main()
{
    struct player p1 =
            {.level = 1, .hp = 100, .f_train = train_fun, .f_pk = pk_fun};
    struct player p2 =
            {.level = 2, .hp = 50, .f_train = train_fun, .f_pk = pk_fun};
    p1.f_train(&p1, 6);
    p2.f_train(&p2, 10);
    p1.f_pk(&p1, &p2);
    return 0;
}

c++中的 class

#include <iostream>
using namespace std;

class player
{
public:
    player(int level=0, int hp=0)
    :level(level), hp(hp){}

    void train(int nums)
    {
        int killnums = hp > nums ? nums : hp;
        level += killnums;
        hp -= killnums;
        cout << "练级:长了" << killnums << " 级。";
        cout << "当前:level=" << level << ",hp=" << hp << endl;
    }

    void pk(player &another)
    {
        int power1 = level * 100 + hp;
        int power2 = another.level * 100 + another.hp;
        if (power1 >= power2)
        {
            cout << "You win" << endl;
        }
        else
        {
            cout << "You loss" << endl;
        }
    }

private:
    int level;
    int hp;
};

int main()
{
    player p1(1, 100);
    player p2(2, 50);
    p1.train(6);
    p2.train(10);
    p1.pk(p2);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/sty945/article/details/82942489