为什么这个函数只被调用一次

时间:2014-08-23 12:10:00

标签: c++

我正在阅读The C++ Programming Language 3rd edition。在第15章(第398页)中,它提供了一个小例子。

class Window {
public:
    virtual void draw() { //sth }
};
class Window_with_border : public virtual Window {
public:
    void own_draw() { //sth }
    void draw() {Window::draw(); own_draw();}
};
class Window_with_menu : public virtual Window {
public:
    void own_draw() { //sth }
    void draw() {Window::draw(); own_draw(); }
};
class Clock : public Window_with_border, public Window_with_menu {
public:
    void own_draw() { //sth }
    void draw() {Window::draw(); Window_with_border::draw(); Window_with_menu::draw(); own_draw(); }
}; 

然后作者说现在可以使用draw()函数编写own_draw()函数,以便任何draw()的调用者只调用Window::draw()一次。

但我认为,当你定义一个Clock对象并调用draw()时,它会被调用三次。喜欢这个

Clock obj;
obj.draw() //The Window::draw() function got invoked three times?

我是对的吗?

更新:对不起,我误读了代码。正确的代码是:

class Clock : public Window_with_border, public Window_with_menu {
public:
    void own_draw() { //sth }
    void draw() {Window::draw(); Window_with_border::own_draw(); Window_with_menu::own_draw(); own_draw(); }
}; 

所以我错了。

1 个答案:

答案 0 :(得分:1)

更长的解释 :令人兴奋的是作者正在谈论的内容 - Window::draw()被调用三次:

  1. 窗口::平局();
  2. Window_with_border ::平局();
  3. Window_with_menu ::平局();
  4. 你可以省略第一个并重写它:

    class Clock : public Window_with_border, public Window_with_menu {
    public:
        void own_draw() { //sth }
        void draw() {
            Window_with_border::draw();
            Window_with_menu::draw();
            own_draw(); }
    };
    

    但仍然是两次,所以决赛应该是:

    class Clock : public Window_with_border, public Window_with_menu {
    public:
        void own_draw() { //sth }
        void draw() {
            Window::draw();
            Window_with_border::own_draw();
            Window_with_menu::own_draw();
            own_draw(); }
    };
    

    OR:

    class Clock : public Window_with_border, public Window_with_menu {
    public:
        void own_draw() { //sth }
        void draw() {
            Window_with_border::draw();
            Window_with_menu::own_draw();
            own_draw(); }
    };