C++内部结构--经典例子

本文通过两个C语言示例展示了如何使用类型转换实现不同对象的行为变化。第一个示例使用了结构体,第二个示例则通过类的方式实现了类似的功能。通过宏定义进行类型转换,程序能够根据对象被视为不同类型来调用相应的方法。

例子1:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct object {
       char name[16];
};

struct person {
       char name[16];

       void sleep() { printf("%s is person, he is sleeping/n", this->name); }
       void study() { printf("%s is person, he is studying/n", this->name); }
};

struct dog {
       char name[16];

       void sleep() { printf("%s is dog, he is sleeping/n", this->name); }
       void bark() { printf("%s is dog, he is barking/n", this->name); }
};

#define bless(object, type) ((type*) object)

int main()
{
       struct object * o = (struct object *) malloc(sizeof(struct object));
       strcpy(o->name, "tom");

       // 先把"tom"变为人
       bless(o, person)->sleep();
       bless(o, person)->study();

       // 再把"tom"变为狗
       bless(o, dog)->sleep();
       bless(o, dog)->bark();

       // 最后,再把"tom"变回人
       bless(o, person)->sleep();
       bless(o, person)->study();
       return 0;
}

// 程序运行时输出:
// tom is person, he is sleeping
// tom is person, he is studying
// tom is dog, he is sleeping
// tom is dog, he is barking
// tom is person, he is sleeping
// tom is person, he is studying

---------------------------------------------------------------------------------------------------------

例子2:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

class object {
public:
       char ccc[20];
       char bbb[20];
};

class person {
private:
       char name[16];

public:
       void sleep() { printf("%s is person, he is sleeping/n", this->name); }
       void study() { printf("%s is person, he is studying/n", this->name); }
};

class dog {
private:
       char name[16];
public:
       void sleep() { printf("%s is dog, he is sleeping/n", this->name); }
       void bark() { printf("%s is dog, he is barking/n", this->name); }
};

#define bless(object, type) ((type*) object)

int main()
{
       object * o = (object *)malloc(sizeof(object));
       strcpy(o->ccc, "tom");

       // 先把"tom"变为人
       bless(o, person)->sleep();
       bless(o, person)->study();

       // 再把"tom"变为狗
       bless(o, dog)->sleep();
       bless(o, dog)->bark();

       // 最后,再把"tom"变回人
       bless(o, person)->sleep();
       bless(o, person)->study();
       return 0;
}

 

// 程序运行时输出:
// tom is person, he is sleeping
// tom is person, he is studying
// tom is dog, he is sleeping
// tom is dog, he is barking
// tom is person, he is sleeping
// tom is person, he is studying

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值