【发布时间】:2015-06-27 01:09:46
【问题描述】:
在Mixing C and C++ Code in the Same Program中给出了下面的例子(这里略略简写到相关部分)。假设 buf.h 包含以下内容:
struct buf {
char* data;
unsigned count;
};
// some declarations of existing C functions for handling buf...
那么建议使用
extern "C" {
#include "buf.h"
}
class mybuf : public buf {
public:
mybuf() : data(0), count(0) { }
// add new methods here (e.g. wrappers for existing C functions)...
};
为了在 C++ 中使用具有附加功能的结构。
但是,这显然会产生以下错误:
error: class `mybuf' does not have any field named `data'
error: class `mybuf' does not have any field named `count'
How can I initialize base class member variables in derived class constructor?、C++: Initialization of inherited field 和 Initialize parent's protected members with initialization list (C++) 中解释了这种情况的原因。
因此,我有以下两个问题:
- 提供的代码是完全错误还是我遗漏了一些相关方面? (毕竟,这篇文章似乎来自一个有信誉的来源)
- 达到预期效果的正确方法是什么(即将 C 结构转换为 C++ 类并添加一些便利方法,例如构造函数等)?
更新:按照建议使用聚合初始化,即
mybuf() : buf{0, 0} {}
有效,但需要 C++11。因此,我添加以下问题:
-
使用C++03,有没有比使用下面的构造函数更好的方法来达到预期的结果?
mybuf() { data = 0; count = 0; }
【问题讨论】:
-
看起来像一个复制和粘贴错误。在同一页的前面,作者实现了一个类
mybuf,它具有data和count成员。 -
为什么要在结构周围放置一个外部“C”?没有必要。
-
@CyberSpock 查看代码的原始来源,这是关于混合 C 和 C++ 代码并且头文件包含一些函数声明,我已经编辑了上面的代码以使其清楚。
-
@godfatherofpolka 无论是 C 还是 C++,结构都是结构。没有理由将其包装在 extern "C" 块中。您的问题不是关于混合 C-C++,而是关于在基类中初始化成员变量。
-
@CyberSpock 是的,你是对的,extern "C" 与问题无关,但我将其保留在那里以提供问题的一些上下文,特别是强调结构是以纯 C 结构形式给出,因此不能在结构级别上进行初始化(如果它是 C++ 结构,这将是显而易见的答案)。
标签: c++ c inheritance struct init