c++ - 在 C++ 中继承 C 结构并将其传递回 C 库是否安全?

标签 c++ c oop inheritance casting

基本上,我想继承 C++ 中的 C 结构(好吧,从字面上看)。我有:

struct foo { // C-side definition
    int sz;
    /* whatever */
    // no virtual destructor, special mechanism
};

class cxx_class { 
    /* something here */
    // no virtual destructor, no need
};

class derived : public foo /*, public cxx_class */ {
    /* some other stuff here */
};

derived 实例(以 foo* 的形式)将被传递回外部库,该库只知道并使用 foo 部分derived(当然)。但问题是(我假设)该库仅使用 c 风格的转换,相当于 C++ 中的 reinterpret_castderived 中的 foo > 必须在内存块的开头。

我想知道这是否是定义的行为,标准是否保证这一点?


换句话说:

编辑: 这两个问题与答案指出的不一样,这部分没有回答。

有时我使用 static_cast 进行向下转换。但是部分代码使用了reinterpret_cast是不是保证两者总是给出相同的答案呢?

最佳答案

derived instances (in form of foo*) will be passed back to the external library which only knows and uses the foo part of derived (of course).

如果您的函数采用foo*,那没关系。即使以 foo 未放在 derived 开头的方式构造您的类型,从 derived* 的转换foo* 发生在知道类型布局的 C++ 代码中。外部函数就不需要担心了。

关于c++ - 在 C++ 中继承 C 结构并将其传递回 C 库是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46534366/

相关文章:

c++ - 在 C++ 中输入时自动更改字符?

c++ - 使用 std::generate_n 用字母字符填充 vector

c - 如何在c中打印特定数据?

java - ArrayList 中的类型不匹配与多态性

java - 在 java 主方法之外初始化一个对象

c++ - 单个 C++ vector 中的多种类型

c++ - 临时调用 operator<<

c - 混合数组的程序中出现未处理的异常

c - 时间复杂度 O(n) [C]

php - 为什么我不能使用这样的开关?