带方法的 C++ 结构,不带方法的 C 声明

标签 c++ c oop c++11 struct

我已经高度怀疑它是可行的并且根本没有风险,但我仍然想确定地知道,所以这是我的事情......

我有一个 C++ 代码,它使用相当大的结构(15-30 个字段)作为容器,作为类构造函数的参数。这些结构的问题是我需要使用 C99 语法声明它们(与 C++ ffs 不兼容):

FooBar fb = { .foo = 12, .bar = 3.4 };

因为我无法想象拥有构造函数,因为在初始化这些结构时可以安全地跳过某些字段,而其他字段则不能,等等(它们仅由“用户提供”数据专门初始化,用户是我发生),有点像他们描述的配置。

无论如何,指出一点,我要使用一个 .h header ,它使用纯 C 语法声明结构,一个 .c 文件包含我初始化的结构,然后我使它们在我的 .cpp 文件中使用外部“C”。它工作得很好......除了我会发现能够为这些结构提供方法非常方便。

所以我的问题是,是否可以像这样声明结构

#ifdef __cplusplus
    // C++ compatible declarations with methods
    struct foobar {
        int foo;
        float bar;

        int method1();
        int method2();
        void method3();
        [etc.]
    };
#else
    /* C compatible declarations, no methods */
    struct foobar {
        int foo;
        float bar;
    };
#endif

这样我就可以在 C++ 中使用一些绑定(bind)到结构的方法(它更优雅,面向 OOP),并且我可以使用 C99 的指定初始化器在我的 C 代码中安全地初始化它们。

我担心的是一些我可能不知道的问题,这些问题最终可能导致 C 代码中的结构偏移与 C++ 代码中的不同。这些问题是否存在?

谢谢

最佳答案

在 C++11 中,如果您的 structstandard-layout,那么它与等效的 C struct 具有相同的布局。构成标准布局结构的规则如下:

A standard-layout class is a class that:

— has no non-static data members of type non-standard-layout class (or array of such types) or reference,

— has no virtual functions (10.3) and no virtual base classes (10.1),

— has the same access control (Clause 11) for all non-static data members,

— has no non-standard-layout base classes,

— either has no non-static data members in the most derived class and at most one base class with non-static data members, or has no base classes with non-static data members, and

— has no base classes of the same type as the first non-static data member.

由于您的结构只有几个公共(public)数据成员和一些非虚拟方法,因此您的结构是标准布局。你可以用更少的重复来表达它

struct foobar {
    int foo;
    float bar;
#ifdef __cplusplus
    int method1();
    int method2();
    void method3();
#endif
};

在以前的 C++ 版本中,您的类型必须是普通旧数据 (POD) 类型,并且有更多限制。但是,您的结构仍然是 POD(没有虚函数、没有构造函数或析构函数、没有基类),因此它仍然与 C 布局兼容。

关于带方法的 C++ 结构,不带方法的 C 声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32641752/

相关文章:

c++ - 构造函数和静态函数

c++ - 无法声明对象

c++ - 无依赖编程

Javascript 构造函数继承助手

python - 寻求目录树数据表示的优雅设计

c++ - Visual C++ Studio,仅重新编译修改后的文件

c++ - Apple Mach-O Linker (Id) 在 C++ 中创建运算符友元函数时出错

c - 我正在编写这段代码来分配一些内存并返回指针,但我收到段错误错误

c - 在初始化中重新使用结构自己的成员是否可靠? (C99)

java - 用java代码实现UML三元关联