如何在C++中更改继承类型的访问类型?

ska*_*lee 4 c++ inheritance

考虑以下示例:

#include <vector>

using namespace std;

class Table: protected vector<int>
{
public:
    iterator begin();
    iterator end();
}
Run Code Online (Sandbox Code Playgroud)

所有向量的方法或者是私有或受保护的,除了begin()end()这是公开的.我可以从课外调用这两种方法Table.但是我无法将它们的返回值分配给变量,因为它们的类型受到保护.

Table t;
t.begin();
Table::iterator iter = t.begin(); // this will fail.
Run Code Online (Sandbox Code Playgroud)

如何Table::iterator公开?

jua*_*nza 6

您可以使用声明来选择std::vector要在班级中公开的部分:

class Table: protected vector<int>
{
public:
    using std::vector<int>::iterator;
    ....
    iterator begin();
    iterator end();
};
Run Code Online (Sandbox Code Playgroud)

如果你只是想使用std::vectorbeginend会员,你可以说

using std::vector<int>::begin;
using std::vector<int>::end;
Run Code Online (Sandbox Code Playgroud)

请注意,这会使公开const和非const重载都公开.