开发者

Type casting a structure member

I have structure(A) and it takes开发者_运维问答 another structure(B) as member. Now i want structure C as member of A instead of B. Both B and C are of same type

typedef struct
{
 int a;
 B b;
}A

typedef struct
{
 int a;
}B

typedef struct
{
 int a;
}C

How can i assign struct C as member instead of B. How to do typecasting Please help


Without knowing why you want to do this, its hard to recommend a strategy. Here are a few options though.

Option 1: Use Templates. (C++ only)

template <type T>
struct A
{
  int a;
  T* t;
};

struct Foo
{
  int a;
};

struct B : public Foo
{
};

struct C : public Foo
{
};

struct A<Foo> A_foo;

struct B;
struct C;

A_foo.t = &B; //OK! This can now take pointer to any class that extends Foo.
A_foo.t = &C; //OK!

Option 2: Make struct A contain a void* (not recommended, you will lose all type safety). (Both C/C++)

struct A 
{
  int a;
  void* foo; // you can now assign any pointer to foo :-S
};


C and C++ are statically typed languages. You can't do it. If you declare something as apple, it will stay as apple until the end of the times.


Although they appear to be the same type (and are, in this simple case, identical) they are considered to be different types by the compiler. This makes sense for more complex cases or in C++ where the type system is more complex than in pure C.

You generally shouldn't rely on compiler tricks or hackery to do this sort of assignment. Instead, do it properly. Either directly assign fields or, to simplify code, create a helper function along these lines:

void ASetBWithC(A *a, C c) {
    assert(a != NULL);
    a->b.a = c.a;
}

C++ also has the assignment operator which you could overload to do your work for you (instead of creating a named helper function) but I suspect this is beyond your current comfort level.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜