比如有 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;
};
1
fyyz 2017 年 9 月 11 日 via Android
继承
|
2
XiaoxiaoPu 2017 年 9 月 11 日 via iPhone
指针强制类型转换
func((struct A *)&b); |
3
momocraft 2017 年 9 月 11 日
#define B A
|
4
Panic 2017 年 9 月 11 日
不能用 union ?那没得救了,重写吧
|
5
northisland 2017 年 9 月 11 日
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; } |
6
northisland 2017 年 9 月 11 日
#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; } |
7
liuminghao233 2017 年 9 月 11 日 via iPhone
强转吧
|
8
acros 2017 年 9 月 11 日
reinterpret_cast
回想了以下,以前工程里面我是没遇到什么机会用这个。 |
9
kofj 2017 年 9 月 11 日
Golang interface 乱入
|
10
fy 2017 年 9 月 11 日
要么 Union,要么类型强转,别跟标准过不去
|
11
gnaggnoyil 2017 年 9 月 11 日
LZ 的头像完美的展示了 C 语言标准面对 LZ 这个需求的时候的反应.
|
12
lrxiao 2017 年 9 月 12 日
|
13
andrewhxism 2017 年 9 月 12 日
@momocraft #3 正解!
|
14
andrewhxism 2017 年 9 月 12 日
@momocraft #3 还有一个办法是 Ctrl + F
|
15
momocraft 2017 年 9 月 12 日
正经的回答:
如果这两个 struct 真的只有名字不同,应该可以用 typedef 或#define。 既然需要当问题拿出来,我猜这两个 struct 不同内容。此时编译器需要的不仅是一个等价的"保证",还需要知道一个 struct 的 member 怎样对应到另一个 struct。 编译器是不会去猜 member 的对应关系的,人都未必猜得出。你可以自己写一些 getter/setter 函数来实现 C 不提供的重载。 |