gpt4 book ai didi

C++,关于继承的基础知识

转载 作者:太空宇宙 更新时间:2023-11-04 16:02:51 25 4
gpt4 key购买 nike

如果我有派生类 PeekingIterator , 基类调用 Iterator .派生类重用基类的成员和成员函数。现在在 C++ 中,继承不继承私有(private)成员。

但在下面的示例中,struct DataData* data是私有(private)成员(member)!所以我的问题是:我们如何调用 Iterator::hasNext()派生类中的函数 PeekingIterator , 当它甚至不继承 struct dataData* data !?

Question Link

// 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 {

}

最佳答案

C++ 中的继承将基类的对象嵌入到子类的对象中。你继承了一切。您无法直接访问所有内容。

现在,由于 hasNext() 是公开的,您可以调用它(如果它受到保护,仍然可以)。 hasNext() 本身可以访问Iterator 的私有(private)部分(由Iterator 添加到PeekingIterator)。所以一切都会起作用。

关于C++,关于继承的基础知识,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40433172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com