比如有 struct A 和 struct B,在需要使用 struct A 的地方也可使用 struct B,而且不会出现错误与警告,例如
int func(struct A *a);
struct B b;
func(&b);
注意,以下答案不能达到目的:
typedef struct A B;
union U {
struct A a;
struct B b;
};
比如有 struct A 和 struct B,在需要使用 struct A 的地方也可使用 struct B,而且不会出现错误与警告,例如
int func(struct A *a);
struct B b;
func(&b);
注意,以下答案不能达到目的:
typedef struct A B;
union U {
struct A a;
struct B b;
};
|
fyyzSep 11, 2017 via Android
1
继承
|
|
XiaoxiaoPuSep 11, 2017 via iPhone
2
指针强制类型转换
func((struct A *)&b); |
|
momocraftSep 11, 2017
3
#define B A
|
|
PanicSep 11, 2017
4
不能用 union ?那没得救了,重写吧
|
|
northislandSep 11, 2017
5
C++版
#include <isotream> struct A { A(int d): digit(d) {} int digit; }; struct B: public Base { B(int d): Base(d) {} }; int function(struct Base& p_base) { std::cout << p_base->digit << std::endl; } int main() { A a(89); B b(64); func(&a); func(&b); return 0; } |
|
northislandSep 11, 2017
6
#include <isotream>
struct A { A(int d): digit(d) {} int digit; }; struct B: public A{ B(int d): A(d) {} }; int function(struct A& p_base) { std::cout << p_base->digit << std::endl; } int main() { struct A a(89); struct B b(64); func(&a); func(&b); return 0; } |
|
liuminghao233Sep 11, 2017 via iPhone
7
强转吧
|
|
acrosSep 11, 2017
8
reinterpret_cast
回想了以下,以前工程里面我是没遇到什么机会用这个。 |
|
kofjSep 11, 2017
9
Golang interface 乱入
|
|
fySep 11, 2017
10
要么 Union,要么类型强转,别跟标准过不去
|
|
gnaggnoyilSep 11, 2017
11
LZ 的头像完美的展示了 C 语言标准面对 LZ 这个需求的时候的反应.
|
|
lrxiaoSep 12, 2017
12
|
|
andrewhxismSep 12, 2017
13
@momocraft #3 正解!
|
|
andrewhxismSep 12, 2017
14
@momocraft #3 还有一个办法是 Ctrl + F
|
|
momocraftSep 12, 2017
15
正经的回答:
如果这两个 struct 真的只有名字不同,应该可以用 typedef 或#define。 既然需要当问题拿出来,我猜这两个 struct 不同内容。此时编译器需要的不仅是一个等价的"保证",还需要知道一个 struct 的 member 怎样对应到另一个 struct。 编译器是不会去猜 member 的对应关系的,人都未必猜得出。你可以自己写一些 getter/setter 函数来实现 C 不提供的重载。 |