When should you use a class vs a struct in C++?

后端 未结 25 1695
误落风尘
误落风尘 2020-11-22 00:18

In what scenarios is it better to use a struct vs a class in C++?

25条回答
  •  一整个雨季
    2020-11-22 00:45

    You can use "struct" in C++ if you are writing a library whose internals are C++ but the API can be called by either C or C++ code. You simply make a single header that contains structs and global API functions that you expose to both C and C++ code as this:

    // C access Header to a C++ library
    #ifdef __cpp
    extern "C" {
    #endif
    
    // Put your C struct's here
    struct foo
    {
        ...
    };
    // NOTE: the typedef is used because C does not automatically generate
    // a typedef with the same name as a struct like C++.
    typedef struct foo foo;
    
    // Put your C API functions here
    void bar(foo *fun);
    
    #ifdef __cpp
    }
    #endif
    

    Then you can write a function bar() in a C++ file using C++ code and make it callable from C and the two worlds can share data through the declared struct's. There are other caveats of course when mixing C and C++ but this is a simplified example.

提交回复
热议问题