mdzz
V2EX  ›  C

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

  •  
  •   mdzz · Sep 11, 2017 · 3299 views
    This topic created in 3344 days ago, the information mentioned may be changed or developed.

    比如有 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;
    };
    
    15 replies  •  2017-09-12 13:18:19 +08:00
    fyyz
    fyyz
    Sep 11, 2017 via Android
    1
    继承
    XiaoxiaoPu
    XiaoxiaoPu
    Sep 11, 2017 via iPhone
    2
    指针强制类型转换

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

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

    既然需要当问题拿出来,我猜这两个 struct 不同内容。此时编译器需要的不仅是一个等价的"保证",还需要知道一个 struct 的 member 怎样对应到另一个 struct。
    编译器是不会去猜 member 的对应关系的,人都未必猜得出。你可以自己写一些 getter/setter 函数来实现 C 不提供的重载。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1432 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 79ms · UTC 05:57 · PVG 13:57 · LAX 21:57 · JFK 00:57
    ♥ Do have faith in what you're doing.