小编Jon*_*ger的帖子

C中的"动态继承"

我编写了以下代码并且它可以工作,但我想知道是否可以确保它在所有x86机器上始终有效.

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

typedef struct Base {
  int a;
  float b;
} Base;

typedef struct Derived1 {
  int a;      // This two members have the same position as in the Base
  float b;

  // adding some other members to this struct
  int otherMember;
  int otherMember2;
} Derived1;

int main()
{
  Base *bases[2];

  // Filling the array with different structs
  bases[0] = (Base*) malloc(sizeof(Base));
  bases[1] = (Base*) malloc(sizeof(Derived1));

  bases[1]->a = 5;
  Derived1 *d1 = (Derived1*) bases[1];

  if(d1->a == 5) …
Run Code Online (Sandbox Code Playgroud)

c oop struct pointers

2
推荐指数
1
解决办法
94
查看次数

标签 统计

c ×1

oop ×1

pointers ×1

struct ×1