有没有办法告诉编译器两个结构体是等价的

2017-09-11 14:16:59 +08:00
 mdzz

比如有 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;
};
2281 次点击
所在节点    C
15 条回复
fyyz
2017-09-11 14:20:23 +08:00
继承
XiaoxiaoPu
2017-09-11 14:29:34 +08:00
指针强制类型转换

func((struct A *)&b);
momocraft
2017-09-11 14:33:48 +08:00
#define B A
Panic
2017-09-11 14:34:43 +08:00
不能用 union ?那没得救了,重写吧
northisland
2017-09-11 14:59:11 +08:00
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;
}
northisland
2017-09-11 15:01:14 +08:00
#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;
}
liuminghao233
2017-09-11 15:14:12 +08:00
强转吧
acros
2017-09-11 15:19:21 +08:00
reinterpret_cast
回想了以下,以前工程里面我是没遇到什么机会用这个。
kofj
2017-09-11 15:55:24 +08:00
Golang interface 乱入
fy
2017-09-11 16:03:34 +08:00
要么 Union,要么类型强转,别跟标准过不去
gnaggnoyil
2017-09-11 20:58:10 +08:00
LZ 的头像完美的展示了 C 语言标准面对 LZ 这个需求的时候的反应.
lrxiao
2017-09-12 04:20:36 +08:00
andrewhxism
2017-09-12 10:45:09 +08:00
@momocraft #3 正解!
andrewhxism
2017-09-12 10:46:12 +08:00
@momocraft #3 还有一个办法是 Ctrl + F
momocraft
2017-09-12 13:18:19 +08:00
正经的回答:

如果这两个 struct 真的只有名字不同,应该可以用 typedef 或#define。

既然需要当问题拿出来,我猜这两个 struct 不同内容。此时编译器需要的不仅是一个等价的"保证",还需要知道一个 struct 的 member 怎样对应到另一个 struct。
编译器是不会去猜 member 的对应关系的,人都未必猜得出。你可以自己写一些 getter/setter 函数来实现 C 不提供的重载。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/389735

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX