2016-11-04 157 views
0

如果我派生类叫做PeekingIterator,而基类叫Iterator。派生类重用基类的成员和成员函数。现在在C++中,继承不会继承私有成员。C++,关于继承的基础知识

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

Question Link在C

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

    } 
+0

我没有看到问题,调用'Iterator :: hasNext()'应该可以正常工作..有什么问题吗? – HazemGomaa

+1

继承DOES包括继承私人成员。他们只是无法访问。如果您希望基类影响它们,请提供public/protected成员函数以对其执行必需的操作(可由派生类使用)。您可以提供其他功能,为私人成员提供指针或引用(通过这些功能,私人可以随后进行更改),但是 - 如果您这样做 - 则可以让成员公开并完成它。 – Peter

+0

愚蠢的问题,如果我在'main'声明'PeekingIterator pi',我能够调用基类函数,比如'pi.Iteratorr :: hasNext()'吗? –

回答

3

继承++嵌入一个基类的对象成子类的一个对象。你继承的一切。你不能直接访问

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

+0

愚蠢的问题,如果我声明'PeekingIterator pi',我可以在'main'中执行'pi.Iteratorr :: hasNext()'吗? –

+0

@Anni_housie是的。这就是你如何调用基类函数。 – StoryTeller

1

所以我的问题是:我们如何才能调用派生类PeekingIterator里面Iterator::hasNext()功能,当它甚至不继承struct dataData* data!?

这是封装的基础 - 你保持数据的私有性(struct data),但你暴露的公共成员函数(hasNext()),所以它可以被派生类访问。

+0

愚蠢的问题,如果我在'main'中声明'PeekingIterator pi',我能够调用基类函数,比如'pi.Iteratorr :: hasNext()'吗? –

1

Iterator::hasNext()可以从PeekingIterator中的任何函数调用。例如:

bool PeekingIterator::hasNext() { 
    bool b = Iterator::hasNext(); 
    .... 
}