考虑以下示例:
#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公开?
您可以使用声明来选择std::vector要在班级中公开的部分:
class Table: protected vector<int>
{
public:
using std::vector<int>::iterator;
....
iterator begin();
iterator end();
};
Run Code Online (Sandbox Code Playgroud)
如果你只是想使用std::vector的begin和end会员,你可以说
using std::vector<int>::begin;
using std::vector<int>::end;
Run Code Online (Sandbox Code Playgroud)
请注意,这会使公开const和非const重载都公开.