c++ - 通过容器的 protected 继承来 boost foreach

标签 c++ inheritance boost foreach

我在使用以下代码时遇到编译时错误。在第 23 行使用 BOOST_FOREACH 时弹出错误:

17 class MyVec: protected std::vector<int>
18 {
19     public:
20         void add(int i) {   this->push_back(i); }
21         void print()
22         {
23             BOOST_FOREACH(int i, *this)
24                 std::cout << i;
25             std::cout << std::endl;
26         }
27 };

但是,如果我在第 17 行将 protected 更改为 public,它会按预期编译和运行。此外,我可以通过使用带有迭代器的标准样板代码来很好地进行迭代。

为什么会这样??任何帮助,将不胜感激! :-)

编辑:这是否意味着我不能在不公开公开 begin() 和 end() 的情况下使用 BOOST_FOREACH? EDTI2:实际上,还需要公开 const_iterator 和迭代器类型。

最佳答案

当您使用 protected 说明符继承时,基类的公共(public)成员在派生类中会受到保护。

BOOST::FOR_EACH 实现可能会尝试调用 begin()end(),但不能。

MyVec 的定义中添加两个 using 声明为我解决了这个问题(我正在使用 gcc):

using std::vector<int>::begin;
using std::vector<int>::end;

如果有助于理解错误,请考虑以下内容:

class MyVec;

void my_foreach(const MyVec&);

class MyVec: protected std::vector<int> {
    void print() {
        my_foreach(*this);
    }
};

void my_foreach(const MyVec& v)
{
    v.begin(); // error std::vector<int> is not an accessible base
}

我不熟悉此宏的确切实现,但我相信这是您遇到的错误的症结所在。如果您有兴趣,请深入了解它的源代码并阅读 this nice article寻求解释。

关于c++ - 通过容器的 protected 继承来 boost foreach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17772179/

相关文章:

Python:继承父类(super class) __init__

c++ - 如何使用 Boost Graph Library 更改图中的边权重?

c++ - 如何在 boost 日期时间中忽略周末和假期?

c++ - 如何在类中实现可选属性

c++ - 在 iOS 应用程序中解压缩 bzip2

java - 继承和创建新类的区别

java - Hibernate @Inheritance 以表为父级, View 为子级

c++ - 如何使用 Boost hana 递归创建 constexpr 列表?

c++ - NanoMsg (NNG) 和 FlatBuffers 是否适合该项目?

c++ - c++中 "unsigned long int"的最大值