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条)

报告相同问题?

悬赏问题

  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样