简体   繁体   中英

C++: How to use extern variables in a struct

I try to implement a piece of software, following a ETSI specification. Now i have to write a struct, in which a variable is declared as extern.

file2.cpp
struct struct_one {
    extern Algo algo;
    int x;
}

file1.cpp
struct struct_two {
    Algo algo;
    char c;
}

So, how do i "tell" the compiler, that the two "algo" variables contain the same things? Is it enough to include file1 in file2?

Or what do i have to do?

Greetings

You can't do that, but you can do it this way:

file1.cpp
struct struct_two {
    Algo algo;
    char c;
}

file2.cpp
struct struct_one {
    explicit struct_one(struct_two& t) : algo(t.algo) {}

    Algo& algo;
    int x;
}

or use combination pattern('has a' relationship):

file1.cpp
struct struct_two {
    Algo algo;
    char c;
}

file2.cpp
struct struct_one {
    struct_two t;
    int x;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM