如果我派生类叫做PeekingIterator
,而基类叫Iterator
。派生类重用基类的成员和成员函数。现在在C++中,继承不会继承私有成员。C++,关于继承的基础知识
但在下面的例子中,struct Data
和Data* data
是私人会员!所以我的问题是:我们如何在派生类PeekingIterator
内部调用Iterator::hasNext()
函数,它甚至不会继承struct data
和Data* data
!?
// Below is the interface for Iterator, which is already defined for you.
// **DO NOT** modify the interface for Iterator.
class Iterator {
struct Data;
Data* data;
public:
Iterator(const vector<int>& nums);
Iterator(const Iterator& iter);
virtual ~Iterator();
// Returns the next element in the iteration.
int next();
// Returns true if the iteration has more elements.
bool hasNext() const;
};
class PeekingIterator : public Iterator {
public:
PeekingIterator(const vector<int>& nums) : Iterator(nums) {
// Initialize any member here.
// **DO NOT** save a copy of nums and manipulate it directly.
// You should only use the Iterator interface methods.
}
// Returns the next element in the iteration without advancing the iterator.
int peek() {
}
// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
int next() {
}
bool hasNext() const {
}
我没有看到问题,调用'Iterator :: hasNext()'应该可以正常工作..有什么问题吗? – HazemGomaa
继承DOES包括继承私人成员。他们只是无法访问。如果您希望基类影响它们,请提供public/protected成员函数以对其执行必需的操作(可由派生类使用)。您可以提供其他功能,为私人成员提供指针或引用(通过这些功能,私人可以随后进行更改),但是 - 如果您这样做 - 则可以让成员公开并完成它。 – Peter
愚蠢的问题,如果我在'main'声明'PeekingIterator pi',我能够调用基类函数,比如'pi.Iteratorr :: hasNext()'吗? –