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

标签 c++ inheritance

如果我有派生类 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/

相关文章:

c++ - 使用 C++ 的 XCode、Visual Studio 和 GitHub

c++ - IRLBot Paper DRUM 实现 - 为什么将键、值对和辅助存储桶分开?

c++ - typedef 单例作为成员变量

c++ - QLongLong 奇怪比较

c++ - SystemC - 在 systemc 模拟中测量并包含文件解析时间

c# - 创建一个抽象函数,它根据继承者接受不同的参数

Django:查询抽象基类

c++ - 重写的虚方法仍然调用基类中的函数

java - 如何将下面的示例转换为实现 Runnable 接口(interface)并重写 run 方法

python - 在python中将属性添加到int值