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

来源:互联网 发布:银行卡芯片 算法rsa 编辑:程序博客网 时间:2024/06/05 14:13

例子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