huyanjie0327 2015-06-10 01:53 采纳率: 100%
浏览 1596
已采纳

这样设计继承有什么好处?

我在阅读thrift源代码的时候,看到了类似于下面的继承设计,为什么不直接重载read, write, 而是要写个read_virt, write_virt这些函数呢?

    #include <boost/shared_ptr.hpp>
    #include <iostream>
    class Parent {
            public:
                    void read() {
                            read_virt();
                    }
                    virtual void read_virt() {

                    }
                    void write() {
                            write_virt();
                    }
                    virtual void write_virt() {

                    }
    };

    class DefaultSon : public Parent {
            public:
                    virtual void read_virt() {
                            std::cout << "DefaultSon read" << std::endl;
                    }
                    virtual void write_virt() {
                            std::cout << "DefaultSon write" << std::endl;
                    }
    };

    template <class Me, class super_ = DefaultSon>
    class VirtualParent: public super_ {
            public:
                    virtual void read_virt() {
                            return static_cast<Me *>(this)->read();
                    }
                    virtual void write_virt() {
                            return static_cast<Me *>(this)->write();
                    }
    };

    class GoodSon : public VirtualParent<GoodSon> {
            public:
                            void read() {
                                    std::cout << "GoodSon read" << std::endl;
                            }
                            void write() {
                                    std::cout << "GoodSon write" << std::endl;
                            }
    };

    class BadSon : public VirtualParent<BadSon> {
            public:
                    void read() {
                                    std::cout << "BadSon read" << std::endl;
                    }
                    void write() {
                                    std::cout << "BadSon read" << std::endl;
                    }
    };

    int main() {
            boost::shared_ptr<Parent> p(new GoodSon());
            p->read();
            p->write();

            boost::shared_ptr<Parent> q(new BadSon());
            q->read();
            q->write();
        }
  • 写回答

6条回答

  • threenewbee 2015-06-10 02:33
    关注

    这个是一个典型的OO设计中的技巧。我们一般管这种设计叫做NVI(Non-Virtual Interface)模式。
    http://blog.csdn.net/acloudhuang/article/details/4465084

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用